{"repo": "MerrimanInd/drawpyo", "n_pairs": 151, "version": "v2_function_scoped", "contexts": {"tests/import_tests/test_import_drawio.py::64": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_geometry_parsing", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/legend_test.py::175": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_update_mapping_rebuilds", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/binary_tree_diagram_test.py::259": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryTreeDiagram"], "enclosing_function": "test_from_dict_nested_structure", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8877}, "tests/diagram_tests/bar_chart_test.py::122": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_update_data_basic", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/base_diagram_test.py::191": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["import_shape_database", "path"], "enclosing_function": "test_import_general_library", "extracted_code": "# Source: src/drawpyo/diagram/base_diagram.py\ndef import_shape_database(file_name: str, relative: bool = False) -> Dict[str, Any]:\n \"\"\"\n This function imports a TOML shape database and returns a dictionary of the\n shapes defined therein. It supports inheritance, meaning that if there is\n an inherit value in any of the shape dictionaries it will attempt to go\n find the inherited master shape and use it as a starting format, but\n overwriting any styles defined in both with the style defined in the child\n object.\n\n Parameters\n ----------\n filename : str\n The path to a TOML file containing a style library database.\n\n Returns\n -------\n data : dict\n A database of shapes defined in the TOML file.\n\n \"\"\"\n # Import the shape and edge definitions\n from sys import version_info\n\n if relative:\n # toml path\n dirname = path.dirname(__file__)\n dirname = path.split(dirname)[0]\n file_name = path.join(dirname, file_name)\n\n if version_info.minor < 11:\n import toml\n\n data = toml.load(file_name)\n else:\n import tomllib\n\n with open(file_name, \"rb\") as f:\n data = tomllib.load(f)\n\n for obj in data.values():\n if \"inherit\" in obj:\n # To make the inheritor styles take precedence the inherited\n # object needs to be updated not the other way around. The copy is\n # created, updated, and replaced.\n new_obj = data[obj[\"inherit\"]]\n new_obj.update(obj)\n obj = new_obj\n\n return data", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1583}, "tests/file_test.py::66": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_multiple_pages", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/import_tests/test_import_drawio.py::63": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_geometry_parsing", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/page_test.py::28": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_grid_settings", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/bar_chart_test.py::278": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_calculate_chart_dimensions_single_bar", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/object_test.py::232": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_rounded_corners", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/edge_test.py::122": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_end_size", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/page_test.py::41": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_page_dimensions", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/xml_base_test.py::19": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/edge_test.py::127": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_start_size", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/diagram_tests/legend_test.py::174": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_update_mapping_rebuilds", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/bar_chart_test.py::291": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_calculate_scale_basic", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/page_test.py::18": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/legend_test.py::72": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Group", "Legend"], "enclosing_function": "test_default_values", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"\n\n\n# Source: src/drawpyo/diagram/objects.py\nclass Group:\n \"\"\"This class allows objects to be grouped together. It then provides a number of geometry functions and properties to move the entire group around.\n\n Currently this object doesn't replicate any of the functionality of groups in the Draw.io app but it may be extended to have that capability in the future.\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n self.objects: List[Object] = kwargs.get(\"objects\", [])\n self.geometry: Geometry = Geometry()\n\n def add_object(self, object: Union[Object, List[Object]]) -> None:\n \"\"\"Adds one or more objects to the group and updates the geometry of the group.\n\n Args:\n object (Object or list): Object or list of objects to be added to the group\n \"\"\"\n if not isinstance(object, list):\n object = [object]\n for o in object:\n if o not in self.objects:\n self.objects.append(o)\n self.update_geometry()\n\n def update_geometry(self) -> None:\n \"\"\"Update the geometry of the group. This includes the left and top coordinates and the width and height of the entire group.\"\"\"\n self.geometry.x = self.left\n self.geometry.y = self.top\n self.geometry.width = self.width\n self.geometry.height = self.height\n\n ###########################################################\n # Passive properties\n ###########################################################\n\n @property\n def left(self) -> Union[int, float]:\n \"\"\"The leftmost X-coordinate of the objects in the group\n\n Returns:\n int: Left edge of the group\n \"\"\"\n return min([obj.geometry.x for obj in self.objects])\n\n @property\n def right(self) -> Union[int, float]:\n \"\"\"The rightmost X-coordinate of the objects in the group\n\n Returns:\n int: Right edge of the group\n \"\"\"\n return max([obj.geometry.x + obj.geometry.width for obj in self.objects])\n\n @property\n def top(self) -> Union[int, float]:\n \"\"\"The topmost Y-coordinate of the objects in the group\n\n Returns:\n int: Top edge of the group\n \"\"\"\n return min([obj.geometry.y for obj in self.objects])\n\n @property\n def bottom(self) -> Union[int, float]:\n \"\"\"The bottommost Y-coordinate of the objects in the group\n\n Returns:\n int: The bottom edge of the group\n \"\"\"\n return max([obj.geometry.y + obj.geometry.height for obj in self.objects])\n\n @property\n def width(self) -> Union[int, float]:\n \"\"\"The width of all the objects in the group\n\n Returns:\n int: Width of the group\n \"\"\"\n return self.right - self.left\n\n @property\n def height(self) -> Union[int, float]:\n \"\"\"The height of all the objects in the group\n\n Returns:\n int: Height of the group\n \"\"\"\n return self.bottom - self.top\n\n @property\n def size(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The size of the group. Returns a tuple of ints, with the width and height.\n\n Returns:\n tuple: A tuple of ints (width, height)\n \"\"\"\n return (self.width, self.height)\n\n ###########################################################\n # Position properties\n ###########################################################\n\n def _move_by_delta(\n self, delta_x: Union[int, float], delta_y: Union[int, float]\n ) -> None:\n \"\"\"Apply position delta to all objects in the group.\n\n Args:\n delta_x: Horizontal offset to apply\n delta_y: Vertical offset to apply\n \"\"\"\n for obj in self.objects:\n obj.position = (obj.geometry.x + delta_x, obj.geometry.y + delta_y)\n self.update_geometry()\n\n @property\n def center_position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The center position of the group. Returns a tuple of ints, with the X and Y coordinate. When this property is set, the coordinates of every object in the group are updated.\n\n Returns:\n tuple: A tuple of ints (X, Y)\n \"\"\"\n return (self.left + self.width / 2, self.top + self.height / 2)\n\n @center_position.setter\n def center_position(\n self, new_center: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n delta_x = new_center[0] - self.center_position[0]\n delta_y = new_center[1] - self.center_position[1]\n self._move_by_delta(delta_x, delta_y)\n\n @property\n def position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The top left position of the group. Returns a tuple of ints, with the X and Y coordinate. When this property is set, the coordinates of every object in the group are updated.\n\n Returns:\n tuple: A tuple of ints (X, Y)\n \"\"\"\n return (self.left, self.top)\n\n @position.setter\n def position(\n self, new_position: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n delta_x = new_position[0] - self.position[0]\n delta_y = new_position[1] - self.position[1]\n self._move_by_delta(delta_x, delta_y)", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 12019}, "tests/diagram_tests/base_diagram_test.py::219": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["drawpyo"], "enclosing_function": "test_geometry_init_custom", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/diagram_tests/object_test.py::141": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_template_chain", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/legend_test.py::103": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_title_object_created", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/legend_test.py::123": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend", "Object", "StandardColor"], "enclosing_function": "test_background_is_added", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"\n\n\n# Source: src/drawpyo/utils/standard_colors.py\nclass StandardColor(str, Enum):\n NONE = \"none\"\n BLACK = \"#000000\"\n WHITE = \"#FFFFFF\"\n GRAY1 = \"#E6E6E6\"\n GRAY2 = \"#CCCCCC\"\n GRAY3 = \"#B3B3B3\"\n GRAY4 = \"#999999\"\n GRAY5 = \"#808080\"\n GRAY6 = \"#666666\"\n GRAY7 = \"#4D4D4D\"\n GRAY8 = \"#333333\"\n GRAY9 = \"#1A1A1A\"\n RED1 = \"#FFCCCC\"\n RED2 = \"#FF9999\"\n RED3 = \"#FF6666\"\n RED4 = \"#FF3333\"\n RED5 = \"#FF0000\"\n RED6 = \"#CC0000\"\n RED7 = \"#990000\"\n RED8 = \"#660000\"\n RED9 = \"#330000\"\n ORANGE1 = \"#FFE6CC\"\n ORANGE2 = \"#FFCC99\"\n ORANGE3 = \"#FFB366\"\n ORANGE4 = \"#FF9933\"\n ORANGE5 = \"#FF8000\"\n ORANGE6 = \"#CC6600\"\n ORANGE7 = \"#994C00\"\n ORANGE8 = \"#663300\"\n ORANGE9 = \"#331A00\"\n YELLOW1 = \"#FFFFCC\"\n YELLOW2 = \"#FFFF99\"\n YELLOW3 = \"#FFFF66\"\n YELLOW4 = \"#FFFF33\"\n YELLOW5 = \"#FFFF00\"\n YELLOW6 = \"#CCCC00\"\n YELLOW7 = \"#999900\"\n YELLOW8 = \"#666600\"\n YELLOW9 = \"#333300\"\n LIME1 = \"#E6FFCC\"\n LIME2 = \"#CCFF99\"\n LIME3 = \"#B3FF66\"\n LIME4 = \"#99FF33\"\n LIME5 = \"#80FF00\"\n LIME6 = \"#66CC00\"\n LIME7 = \"#4D9900\"\n LIME8 = \"#336600\"\n LIME9 = \"#1A3300\"\n GREEN1 = \"#CCFFCC\"\n GREEN2 = \"#99FF99\"\n GREEN3 = \"#66FF66\"\n GREEN4 = \"#33FF33\"\n GREEN5 = \"#00FF00\"\n GREEN6 = \"#00CC00\"\n GREEN7 = \"#009900\"\n GREEN8 = \"#006600\"\n GREEN9 = \"#003300\"\n EMERALD1 = \"#CCFFE6\"\n EMERALD2 = \"#99FFCC\"\n EMERALD3 = \"#66FFB3\"\n EMERALD4 = \"#33FF99\"\n EMERALD5 = \"#00FF80\"\n EMERALD6 = \"#00CC66\"\n EMERALD7 = \"#00994D\"\n EMERALD8 = \"#006633\"\n EMERALD9 = \"#00331A\"\n CYAN1 = \"#CCFFFF\"\n CYAN2 = \"#99FFFF\"\n CYAN3 = \"#66FFFF\"\n CYAN4 = \"#33FFFF\"\n CYAN5 = \"#00FFFF\"\n CYAN6 = \"#00CCCC\"\n CYAN7 = \"#009999\"\n CYAN8 = \"#006666\"\n CYAN9 = \"#003333\"\n BLUE1 = \"#CCE5FF\"\n BLUE2 = \"#99CCFF\"\n BLUE3 = \"#66B2FF\"\n BLUE4 = \"#3399FF\"\n BLUE5 = \"#007FFF\"\n BLUE6 = \"#0066CC\"\n BLUE7 = \"#004C99\"\n BLUE8 = \"#003366\"\n BLUE9 = \"#001933\"\n INDIGO1 = \"#CCCCFF\"\n INDIGO2 = \"#9999FF\"\n INDIGO3 = \"#6666FF\"\n INDIGO4 = \"#3333FF\"\n INDIGO5 = \"#0000FF\"\n INDIGO6 = \"#0000CC\"\n INDIGO7 = \"#000099\"\n INDIGO8 = \"#000066\"\n INDIGO9 = \"#000033\"\n PURPLE1 = \"#E5CCFF\"\n PURPLE2 = \"#CC99FF\"\n PURPLE3 = \"#B266FF\"\n PURPLE4 = \"#9933FF\"\n PURPLE5 = \"#7F00FF\"\n PURPLE6 = \"#6600CC\"\n PURPLE7 = \"#6600CC\"\n PURPLE8 = \"#330066\"\n PURPLE9 = \"#190033\"\n MAGENTA1 = \"#FFCCFF\"\n MAGENTA2 = \"#FF99CC\"\n MAGENTA3 = \"#FF66CC\"\n MAGENTA4 = \"#FF33FF\"\n MAGENTA5 = \"#FF00FF\"\n MAGENTA6 = \"#CC00CC\"\n MAGENTA7 = \"#990099\"\n MAGENTA8 = \"#660066\"\n MAGENTA9 = \"#330033\"\n CRIMSON1 = \"#FFCCE6\"\n CRIMSON2 = \"#FF99CC\"\n CRIMSON3 = \"#FF66B3\"\n CRIMSON4 = \"#FF3399\"\n CRIMSON5 = \"#FF0080\"\n CRIMSON6 = \"#CC0066\"\n CRIMSON7 = \"#99004D\"\n CRIMSON8 = \"#660033\"\n CRIMSON9 = \"#33001A\"\n\n\n# Source: src/drawpyo/diagram/objects.py\nclass Object(DiagramBase):\n \"\"\"\n The Object class is the base object for all shapes in Draw.io.\n\n More information about objects are in the Usage documents at [Usage - Objects](../../usage/objects).\n \"\"\"\n\n ###########################################################\n # Initialization Functions\n ###########################################################\n\n def __init__(\n self, value: str = \"\", position: Tuple[int, int] = (0, 0), **kwargs: Any\n ) -> None:\n \"\"\"A Object can be initialized with as many or as few of its styling attributes as is desired.\n\n Args:\n value (str, optional): The text to fill the object with. Defaults to \"\".\n position (tuple, optional): The position of the object in pixels, in (X, Y). Defaults to (0, 0).\n\n Keyword Args:\n aspect (optional): Aspect ratio handling. Defaults to None.\n autocontract (bool, optional): Whether to contract to fit the child objects. Defaults to False.\n autosize_margin (int, optional): What margin in pixels to leave around the child objects. Defaults to 20.\n autosize_to_children (bool, optional): Whether to autoexpand when child objects are added. Defaults to False.\n baseStyle (optional): Base style for the object. Defaults to None.\n children (list of Objects, optional): The subobjects to add to this object as a parent. Defaults to [].\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n comic (bool, optional): Add comic styling to the object. Defaults to None.\n fillColor (Union[str, StandardColor], optional): The object fill color. Defaults to None.\n glass (bool, optional): Apply glass styling to the object. Defaults to None.\n height (int, optional): The height of the object in pixels. Defaults to 80.\n in_edges (list, optional): List of incoming edges to this object. Defaults to [].\n line_pattern (str, optional): The stroke style of the object. Defaults to \"solid\".\n opacity (int, optional): The object's opacity, 0-100. Defaults to None.\n out_edges (list, optional): List of outgoing edges from this object. Defaults to [].\n parent (Object, optional): The parent object (container, etc) of this object. Defaults to None.\n position_rel_to_parent (tuple, optional): The position of the object relative to the parent in pixels, in (X, Y).\n rounded (int or bool, optional): Whether to round the corners of the shape. Defaults to 0.\n shadow (bool, optional): Add a shadow to the object. Defaults to None.\n sketch (bool, optional): Add sketch styling to the object. Defaults to None.\n strokeColor (Union[str, StandardColor], optional): The object stroke color. Defaults to None.\n template_object (Object, optional): Another object to copy the style_attributes from. Defaults to None.\n text_format (TextFormat, optional): Formatting specifically around text. Defaults to TextFormat().\n vertex (int, optional): Vertex flag for the object. Defaults to 1.\n whiteSpace (str, optional): White space handling. Defaults to \"wrap\".\n width (int, optional): The width of the object in pixels. Defaults to 120.\n \"\"\"\n super().__init__(**kwargs)\n self._style_attributes: List[str] = [\n \"whiteSpace\",\n \"rounded\",\n \"fillColor\",\n \"strokeColor\",\n \"glass\",\n \"shadow\",\n \"comic\",\n \"sketch\",\n \"opacity\",\n \"dashed\",\n ]\n\n self.geometry: Geometry = Geometry(parent_object=self)\n\n # Subobjecting\n # If there is a parent passed in, disable that parents\n # autoexpanding until position is set\n if \"parent\" in kwargs:\n parent: Object = kwargs.get(\"parent\")\n old_parent_autosize: bool = parent.autosize_to_children\n parent.autoexpand = False\n self.parent: Optional[Object] = parent\n else:\n self._parent: Optional[Object] = None\n self.children: List[Object] = kwargs.get(\"children\", [])\n self.autosize_to_children: bool = kwargs.get(\"autosize_to_children\", False)\n self.autocontract: bool = kwargs.get(\"autocontract\", False)\n self.autosize_margin: int = kwargs.get(\"autosize_margin\", 20)\n\n # Geometry\n self.position: Optional[tuple] = position\n # Since the position is already set to either a passed in arg or the default this will\n # either override that default position or redundantly reset the position to the same value\n self.position_rel_to_parent: Optional[tuple] = kwargs.get(\n \"position_rel_to_parent\", position\n )\n self.width: int = kwargs.get(\"width\", 120)\n self.height: int = kwargs.get(\"height\", 80)\n self.vertex: int = kwargs.get(\"vertex\", 1)\n\n # TODO enumerate to fixed\n self.aspect = kwargs.get(\"aspect\", None)\n\n # Style\n self.baseStyle: Optional[str] = kwargs.get(\"baseStyle\", None)\n\n self.rounded: Optional[bool] = kwargs.get(\"rounded\", 0)\n self.whiteSpace: Optional[str] = kwargs.get(\"whiteSpace\", \"wrap\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"strokeColor\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fillColor\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n self.glass: Optional[bool] = kwargs.get(\"glass\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.comic: Optional[bool] = kwargs.get(\"comic\", None)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.line_pattern: Optional[str] = kwargs.get(\"line_pattern\", \"solid\")\n\n self.out_edges: List[Any] = kwargs.get(\"out_edges\", [])\n self.in_edges: List[Any] = kwargs.get(\"in_edges\", [])\n\n self.xml_class: str = \"mxCell\"\n\n if \"template_object\" in kwargs:\n self.template_object: Object = kwargs.get(\"template_object\")\n self._apply_style_from_template(self.template_object)\n self.width = self.template_object.width\n self.height = self.template_object.height\n\n # Content\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.value: Optional[str] = value\n\n # If a parent was passed in, reactivate the parents autoexpanding and update it\n if \"parent\" in kwargs:\n self.parent.autosize_to_children = old_parent_autosize\n self.update_parent()\n\n logger.debug(f\"🔲 Object created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A more informative representation for debugging.\n \"\"\"\n parts = []\n\n # Geometry\n parts.append(f\"pos: {self.position}\")\n parts.append(f\"size: ({self.width}x{self.height})\")\n\n # Parent info\n if getattr(self, \"parent\", None):\n parts.append(f\"parent: {self.parent.__class__.__name__}\")\n\n # Child count\n if getattr(self, \"children\", None):\n parts.append(f\"children: {len(self.children)}\")\n\n joined = \" | \".join(parts)\n return f\"{self.value} | {joined}\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def __delete__(self) -> None:\n self.page.remove_object(self)\n\n @classmethod\n def create_from_template_object(\n cls,\n template_object: \"Object\",\n value: Optional[str] = None,\n position: Optional[Tuple[int, int]] = None,\n page: Optional[Any] = None,\n ) -> \"Object\":\n \"\"\"Object can be instantiated from another object. This will initialize the Object with the same formatting, then set a new position and value.\n\n Args:\n template_object (Object): Another drawpyo Object to use as a template\n value (str, optional): The text contents of the object. Defaults to None.\n position (tuple, optional): The position where the object should be placed. Defaults to (0, 0).\n page (Page, optional): The Page object to place the object on. Defaults to None.\n\n Returns:\n Object: The newly created object\n \"\"\"\n new_obj: Object = cls(\n value=value,\n page=page,\n width=template_object.width,\n height=template_object.height,\n template_object=template_object,\n )\n if position is not None:\n new_obj.position = position\n if value is not None:\n new_obj.value = value\n return new_obj\n\n @classmethod\n def create_from_style_string(cls, style_string: str) -> \"Object\":\n \"\"\"Objects can be instantiated from a style string. These strings are most easily found in the Draw.io app, by styling an object as desired then right-clicking and selecting \"Edit Style\". Copying that text into this function will generate an object styled the same.\n\n Args:\n style_string (str): A Draw.io generated style string.\n\n Returns:\n Object: An object formatted with the style string\n \"\"\"\n cls.apply_style_from_string(style_string)\n return cls\n\n @classmethod\n def create_from_library(\n cls, library: Union[str, Dict[str, Any]], obj_name: str\n ) -> \"Object\":\n \"\"\"This function generates a Object from a library. The library can either be custom imported from a TOML or the name of one of the built-in Draw.io libraries.\n\n Any keyword arguments that can be passed in to a Object creation can be passed into this function and it will format the base object. However, the styling in the library will overwrite that formatting.\n\n Args:\n library (str or dict): The library containing the object\n obj_name (str): The name of the object in the library to generate\n\n Returns:\n Object: An object with the style from the library\n \"\"\"\n new_obj: Object = cls()\n new_obj.format_as_library_object(library, obj_name)\n return new_obj\n\n def format_as_library_object(\n self, library: Union[str, Dict[str, Any]], obj_name: str\n ) -> None:\n \"\"\"This function applies the style from a library to an existing object. The library can either be custom imported from a TOML or the name of one of the built-in Draw.io libraries.\n\n Args:\n library (str or dict): The library containing the object\n obj_name (str): The name of the object in the library to generate\n\n Raises:\n ValueError: If the library or object name is invalid or not found.\n KeyError: If required keys are missing from the object definition.\n \"\"\"\n if type(library) == str:\n if library in base_libraries:\n library_dict: Dict[str, Any] = base_libraries[library]\n if obj_name in library_dict:\n obj_dict: Dict[str, Any] = library_dict[obj_name]\n self.apply_attribute_dict(obj_dict)\n else:\n raise ValueError(\n f\"Object '{obj_name}' not found in library '{library}'. \"\n f\"Available objects: {', '.join(list(library_dict.keys())[:10])}\"\n + (\"...\" if len(library_dict) > 10 else \"\")\n )\n else:\n raise ValueError(\n f\"Library '{library}' not found in base_libraries. \"\n f\"Available libraries: {', '.join(base_libraries.keys())}\"\n )\n elif type(library) == dict:\n if obj_name not in library:\n raise ValueError(\n f\"Object '{obj_name}' not found in provided library dictionary. \"\n f\"Available objects: {', '.join(list(library.keys())[:10])}\"\n + (\"...\" if len(library) > 10 else \"\")\n )\n obj_dict: Dict[str, Any] = library[obj_name]\n\n # Validate that we have at least some usable data\n if not obj_dict:\n raise ValueError(\n f\"Object '{obj_name}' has no properties defined in the library\"\n )\n\n # Warn if baseStyle is missing (common in mxlibrary shapes)\n if \"baseStyle\" not in obj_dict:\n logger.warning(\n f\"Object '{obj_name}' does not have a 'baseStyle' property. \"\n f\"This may result in a shape without styling.\"\n )\n\n self.apply_attribute_dict(obj_dict)\n else:\n raise ValueError(\n f\"Invalid library type: expected str or dict, got {type(library).__name__}\"\n )\n\n @property\n def attributes(self) -> Dict[str, Any]:\n return {\n \"id\": self.id,\n \"value\": self.value,\n \"style\": self.style,\n \"vertex\": self.vertex,\n \"parent\": self.xml_parent_id,\n }\n\n ###########################################################\n # Style templates\n ###########################################################\n\n @property\n def line_styles(self) -> Dict[str, Any]:\n return line_styles\n\n @property\n def container(self) -> Dict[Optional[str], None]:\n return container\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def line_pattern(self) -> Optional[str]:\n \"\"\"Two properties are enumerated together into line_pattern: dashed and dashPattern. line_pattern simplifies this with an external database that contains the dropdown options from the Draw.io app then outputs the correct combination of dashed and dashPattern.\n\n However in some cases dashed and dashpattern need to be set individually, such as when formatting from a style string. In that case, the setters for those two attributes will disable the other.\n\n Returns:\n str: The line style\n \"\"\"\n return self._line_pattern\n\n @line_pattern.setter\n def line_pattern(self, value: str) -> None:\n if value in line_styles.keys():\n self._line_pattern = value\n else:\n raise ValueError(\n \"{0} is not an allowed value of line_pattern\".format(value)\n )\n\n @property\n def dashed(self) -> Optional[Union[bool, Any]]:\n \"\"\"This is one of the properties that defines the line style. Along with dashPattern, it can be overriden by setting line_pattern or set directly.\n\n Returns:\n str: Whether the object stroke is dashed.\n \"\"\"\n if self._line_pattern is None:\n return self._dashed\n else:\n return line_styles[self._line_pattern]\n\n @dashed.setter\n def dashed(self, value: bool) -> None:\n self._line_pattern = None\n self._dashed = value\n\n @property\n def dashPattern(self) -> Optional[Union[str, Any]]:\n \"\"\"This is one of the properties that defines the line style. Along with dashed, it can be overriden by setting line_pattern or set directly.\n\n Returns:\n str: What style the object stroke is dashed with.\n \"\"\"\n if self._line_pattern is None:\n return self._dashPattern\n else:\n return line_styles[self._line_pattern]\n\n @dashPattern.setter\n def dashPattern(self, value: str) -> None:\n self._line_pattern = None\n self._dashPattern = value\n\n ###########################################################\n # Geometry properties\n ###########################################################\n\n @property\n def width(self) -> int:\n \"\"\"This property makes geometry.width available to the owning class for ease of access.\"\"\"\n return self.geometry.width\n\n @width.setter\n def width(self, value: int) -> None:\n self.geometry.width = value\n self.update_parent()\n\n @property\n def height(self) -> int:\n \"\"\"This property makes geometry.height available to the owning class for ease of access.\"\"\"\n return self.geometry.height\n\n @height.setter\n def height(self, value: int) -> None:\n self.geometry.height = value\n self.update_parent()\n\n # Position property\n @property\n def position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The position of the object on the page. This is the top left corner. It's set with a tuple of ints, X and Y respectively.\n\n (X, Y)\n\n Returns:\n tuple: A tuple of ints describing the top left corner position of the object\n \"\"\"\n if self.parent is not None:\n return (\n self.geometry.x + self.parent.position[0],\n self.geometry.y + self.parent.position[1],\n )\n return (self.geometry.x, self.geometry.y)\n\n @position.setter\n def position(self, value: Tuple[Union[int, float], Union[int, float]]) -> None:\n if self.parent is not None:\n self.geometry.x = value[0] - self.parent.position[0]\n self.geometry.y = value[1] - self.parent.position[1]\n else:\n self.geometry.x = value[0]\n self.geometry.y = value[1]\n self.update_parent()\n\n # Position Rel to Parent\n @property\n def position_rel_to_parent(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The position of the object relative to its parent (container). If there's no parent this will be relative to the page. This is the top left corner. It's set with a tuple of ints, X and Y respectively.\n\n (X, Y)\n\n Returns:\n tuple: A tuple of ints describing the top left corner position of the object\n \"\"\"\n return (self.geometry.x, self.geometry.y)\n\n @position_rel_to_parent.setter\n def position_rel_to_parent(\n self, value: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n self.geometry.x = value[0]\n self.geometry.y = value[1]\n self.update_parent()\n\n @property\n def center_position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The position of the object on the page. This is the center of the object. It's set with a tuple of ints, X and Y respectively.\n\n (X, Y)\n\n Returns:\n tuple: A tuple of ints describing the center position of the object\n \"\"\"\n x: Union[int, float] = self.geometry.x + self.geometry.width / 2\n y: Union[int, float] = self.geometry.y + self.geometry.height / 2\n return (x, y)\n\n @center_position.setter\n def center_position(\n self, position: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n self.geometry.x = position[0] - self.geometry.width / 2\n self.geometry.y = position[1] - self.geometry.height / 2\n\n ###########################################################\n # Subobjects\n ###########################################################\n # TODO add to documentation\n\n @property\n def xml_parent_id(self) -> Union[int, Any]:\n if self.parent is not None:\n return self.parent.id\n return 1\n\n @property\n def parent(self) -> Optional[\"Object\"]:\n \"\"\"The parent object that owns this object. This is usually a container of some kind but can be any other object.\n\n Returns:\n Object: the parent object.\n \"\"\"\n return self._parent\n\n @parent.setter\n def parent(self, value: Optional[\"Object\"]) -> None:\n if isinstance(value, Object):\n # value.add_object(self)\n value.children.append(self)\n self.update_parent()\n self._parent = value\n\n def add_object(self, child_object: \"Object\") -> None:\n \"\"\"Adds a child object to this object, sets the child objects parent, and autoexpands this object if set to.\n\n Args:\n child_object (Object): object to add as a child\n \"\"\"\n child_object._parent = self # Bypass the setter to prevent a loop\n self.children.append(child_object)\n if self.autosize_to_children:\n self.resize_to_children()\n\n def remove_object(self, child_object: \"Object\") -> None:\n \"\"\"Removes a child object from this object, clears the child objects parent, and autoexpands this object if set to.\n\n Args:\n child_object (Object): object to remove as a child\n \"\"\"\n child_object._parent = None # Bypass the setter to prevent a loop\n self.children.remove(child_object)\n if self.autosize_to_children:\n self.resize_to_children()\n\n def update_parent(self) -> None:\n \"\"\"If a parent object is set and the parent is set to autoexpand, then autoexpand it.\"\"\"\n # This function needs to be callable prior to the parent being set during init,\n # hence the hasattr() check.\n if (\n hasattr(self, \"_parent\")\n and self.parent is not None\n and self.parent.autosize_to_children\n ):\n # if the parent is autoexpanding, call the autoexpand function\n self.parent.resize_to_children()\n\n def resize_to_children(self) -> None:\n \"\"\"If the object contains children (is a container, parent, etc) then expand the size and position to fit all of the children.\n\n By default this function will never shrink the size of the object, only expand it. The contract input can be set for that behavior.\n\n Args:\n contract (bool, optional): Contract the parent object to hug the children. Defaults to False.\n \"\"\"\n # Get current extents\n if len(self.children) == 0:\n return\n if self.autocontract:\n topmost: Union[int, float] = 65536\n bottommost: Union[int, float] = -65536\n leftmost: Union[int, float] = 65536\n rightmost: Union[int, float] = -65536\n else:\n topmost: Union[int, float] = self.position[1]\n bottommost: Union[int, float] = self.position[1] + self.height\n leftmost: Union[int, float] = self.position[0]\n rightmost: Union[int, float] = self.position[0] + self.width\n\n # Check all child objects for extents\n for child_object in self.children:\n topmost = min(topmost, child_object.position[1] - self.autosize_margin)\n bottommost = max(\n bottommost,\n child_object.position[1] + child_object.height + self.autosize_margin,\n )\n leftmost = min(leftmost, child_object.position[0] - self.autosize_margin)\n rightmost = max(\n rightmost,\n child_object.position[0] + child_object.width + self.autosize_margin,\n )\n\n # Set self extents to furthest positions\n self.move_wo_children((leftmost, topmost))\n self.width = rightmost - leftmost\n self.height = bottommost - topmost\n\n def move_wo_children(\n self, position: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n \"\"\"Move the parent object relative to the page without moving the children relative to the page.\n\n Args:\n position (Tuple of Ints): The target position for the parent object.\n \"\"\"\n # Disable autoexpand to avoid recursion from child_objects\n # attempting to update their autoexpanding parent upon a move\n old_autoexpand: bool = self.autosize_to_children\n self.autosize_to_children = False\n\n # Move children to counter upcoming parent move\n pos_delta: List[Union[int, float]] = [\n old_pos - new_pos for old_pos, new_pos in zip(self.position, position)\n ]\n for child_object in self.children:\n child_object.position = (\n child_object.position[0] + pos_delta[0],\n child_object.position[1] + pos_delta[1],\n )\n\n # Set new position and re-enable autoexpand\n self.position = position\n self.autosize_to_children = old_autoexpand\n\n ###########################################################\n # Edge Tracking\n ###########################################################\n\n def add_out_edge(self, edge: Any) -> None:\n \"\"\"Add an edge out of the object. If an edge is created with this object set as the source this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object originating at this object\n \"\"\"\n self.out_edges.append(edge)\n\n def remove_out_edge(self, edge: Any) -> None:\n \"\"\"Remove an edge out of the object. If an edge linked to this object has the source changed or removed this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object originating at this object\n \"\"\"\n self.out_edges.remove(edge)\n\n def add_in_edge(self, edge: Any) -> None:\n \"\"\"Add an edge into the object. If an edge is created with this object set as the target this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object ending at this object\n \"\"\"\n self.in_edges.append(edge)\n\n def remove_in_edge(self, edge: Any) -> None:\n \"\"\"Remove an edge into the object. If an edge linked to this object has the target changed or removed this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object ending at this object\n \"\"\"\n self.in_edges.remove(edge)\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def xml(self) -> str:\n \"\"\"\n Returns the XML object for the Object: the opening tag with the style attributes, the value, and the closing tag.\n\n Example:\n Text in object\n\n Returns:\n str: A single XML tag containing the object name, style attributes, and a closer.\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 36509}, "tests/diagram_tests/pie_chart_test.py::167": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_update_data_adjusts_colors", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/diagram_tests/object_test.py::57": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_with_dimensions", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/bar_chart_test.py::234": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_custom_tick_count", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/bar_chart_test.py::91": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_mixed_int_float_values", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/pie_chart_test.py::267": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_single_slice_full_circle", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/diagram_tests/color_management_test.py::205": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": [], "enclosing_function": "test_hierarchy_defaults_used_when_both_missing", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/diagram_tests/object_test.py::36": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/xml_base_test.py::26": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_custom_id", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/import_tests/test_mxlibrary_import.py::30": {"resolved_imports": ["src/drawpyo/drawio_import/mxlibrary_parser.py", "src/drawpyo/__init__.py"], "used_names": ["parse_mxlibrary"], "enclosing_function": "test_parse_mxlibrary_parsed_correctly", "extracted_code": "# Source: src/drawpyo/drawio_import/mxlibrary_parser.py\ndef parse_mxlibrary(content: str) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:\n \"\"\"\n Parses an mxlibrary file content and extracts shape definitions.\n\n Args:\n content: The string content of the mxlibrary file.\n\n Returns:\n A tuple of (shapes_dict, errors_list) where:\n - shapes_dict: Dictionary with keys as titles and values as dicts containing\n properties like baseStyle, width, height, and xml_class.\n - errors_list: List of error messages for shapes that couldn't be parsed.\n \"\"\"\n errors: List[str] = []\n clean_content = (\n content.replace(\"\", \"\").replace(\"\", \"\").strip()\n )\n\n try:\n data = json.loads(clean_content)\n except json.JSONDecodeError as e:\n # Try to extract JSON array from content\n start = content.find(\"[\")\n end = content.rfind(\"]\")\n if start != -1 and end != -1:\n try:\n data = json.loads(content[start : end + 1])\n except json.JSONDecodeError:\n errors.append(f\"Failed to parse JSON content: {str(e)}\")\n return {}, errors\n else:\n errors.append(f\"No valid JSON array found in content: {str(e)}\")\n return {}, errors\n\n shapes: Dict[str, Dict[str, Any]] = {}\n\n if not isinstance(data, list):\n errors.append(f\"Expected JSON array, got {type(data).__name__}\")\n return {}, errors\n\n for idx, item in enumerate(data):\n if not isinstance(item, dict):\n errors.append(f\"Item {idx}: Expected dict, got {type(item).__name__}\")\n continue\n\n title = item.get(\"title\", \"Untitled\")\n w = item.get(\"w\", 0)\n h = item.get(\"h\", 0)\n xml_encoded = item.get(\"xml\")\n\n if not xml_encoded:\n errors.append(f\"Item {idx} ({title}): Missing 'xml' field\")\n continue\n\n xml_str = html.unescape(xml_encoded)\n\n try:\n try:\n root_element = ET.fromstring(xml_str)\n except ET.ParseError:\n root_element = ET.fromstring(f\"{xml_str}\")\n\n main_cell = None\n cells = []\n\n if root_element.tag == \"mxCell\":\n cells.append(root_element)\n\n for cell in root_element.iter(\"mxCell\"):\n cells.append(cell)\n\n for cell in cells:\n if cell.get(\"vertex\") == \"1\":\n main_cell = cell\n break\n\n if main_cell is None and cells:\n main_cell = cells[0]\n\n if main_cell is not None:\n style = main_cell.get(\"style\", \"\")\n\n shapes[title] = {\n \"baseStyle\": style,\n \"width\": w,\n \"height\": h,\n \"xml_class\": \"mxCell\",\n }\n else:\n errors.append(f\"Item {idx} ({title}): No valid mxCell found in XML\")\n\n except ET.ParseError as e:\n errors.append(f\"Item {idx} ({title}): XML parse error - {str(e)}\")\n except Exception as e:\n errors.append(f\"Item {idx} ({title}): Unexpected error - {str(e)}\")\n\n return shapes, errors", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 3280}, "tests/diagram_tests/color_management_test.py::215": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme"], "enclosing_function": "test_hierarchy_font_object_specific_override", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/object_test.py::56": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_with_dimensions", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/base_diagram_test.py::176": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["style_str_from_dict"], "enclosing_function": "test_complex_style_dict", "extracted_code": "# Source: src/drawpyo/diagram/base_diagram.py\ndef style_str_from_dict(style_dict: Dict[str, Any]) -> str:\n \"\"\"\n This function returns a concatenated style string from a style dictionary.\n This format is:\n baseStyle;attr1=value;attr2=value\n It will concatenate the key:value pairs with the appropriate semicolons and\n equals except for the baseStyle, which it will prepend to the front with no\n equals sign.\n\n Parameters\n ----------\n style_dict : dict\n A dictionary of style:value pairs.\n\n Returns\n -------\n str\n A string with the style_dicts values concatenated correctly.\n\n \"\"\"\n if \"baseStyle\" in style_dict:\n style_str = [style_dict.pop(\"baseStyle\")]\n else:\n style_str = []\n style_str = style_str + [\n \"{0}={1}\".format(att, style)\n for (att, style) in style_dict.items()\n if style != \"\" and style != None\n ]\n return \";\".join(style_str)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 951}, "tests/xml_base_test.py::30": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_custom_xml_class", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/binary_tree_diagram_test.py::60": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject"], "enclosing_function": "test_move_child_between_parents_using_properties", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4036}, "tests/diagram_tests/color_management_test.py::105": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme", "pytest"], "enclosing_function": "test_invalid_hex_raises_value_error", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/pie_chart_test.py::517": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_default_size_constant", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/page_test.py::140": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_object", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/import_tests/test_import_drawio.py::38": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_diagram_loads", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/import_tests/test_mxlibrary_import.py::52": {"resolved_imports": ["src/drawpyo/drawio_import/mxlibrary_parser.py", "src/drawpyo/__init__.py"], "used_names": ["parse_mxlibrary"], "enclosing_function": "test_parse_mxlibrary_missing_xml_field", "extracted_code": "# Source: src/drawpyo/drawio_import/mxlibrary_parser.py\ndef parse_mxlibrary(content: str) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:\n \"\"\"\n Parses an mxlibrary file content and extracts shape definitions.\n\n Args:\n content: The string content of the mxlibrary file.\n\n Returns:\n A tuple of (shapes_dict, errors_list) where:\n - shapes_dict: Dictionary with keys as titles and values as dicts containing\n properties like baseStyle, width, height, and xml_class.\n - errors_list: List of error messages for shapes that couldn't be parsed.\n \"\"\"\n errors: List[str] = []\n clean_content = (\n content.replace(\"\", \"\").replace(\"\", \"\").strip()\n )\n\n try:\n data = json.loads(clean_content)\n except json.JSONDecodeError as e:\n # Try to extract JSON array from content\n start = content.find(\"[\")\n end = content.rfind(\"]\")\n if start != -1 and end != -1:\n try:\n data = json.loads(content[start : end + 1])\n except json.JSONDecodeError:\n errors.append(f\"Failed to parse JSON content: {str(e)}\")\n return {}, errors\n else:\n errors.append(f\"No valid JSON array found in content: {str(e)}\")\n return {}, errors\n\n shapes: Dict[str, Dict[str, Any]] = {}\n\n if not isinstance(data, list):\n errors.append(f\"Expected JSON array, got {type(data).__name__}\")\n return {}, errors\n\n for idx, item in enumerate(data):\n if not isinstance(item, dict):\n errors.append(f\"Item {idx}: Expected dict, got {type(item).__name__}\")\n continue\n\n title = item.get(\"title\", \"Untitled\")\n w = item.get(\"w\", 0)\n h = item.get(\"h\", 0)\n xml_encoded = item.get(\"xml\")\n\n if not xml_encoded:\n errors.append(f\"Item {idx} ({title}): Missing 'xml' field\")\n continue\n\n xml_str = html.unescape(xml_encoded)\n\n try:\n try:\n root_element = ET.fromstring(xml_str)\n except ET.ParseError:\n root_element = ET.fromstring(f\"{xml_str}\")\n\n main_cell = None\n cells = []\n\n if root_element.tag == \"mxCell\":\n cells.append(root_element)\n\n for cell in root_element.iter(\"mxCell\"):\n cells.append(cell)\n\n for cell in cells:\n if cell.get(\"vertex\") == \"1\":\n main_cell = cell\n break\n\n if main_cell is None and cells:\n main_cell = cells[0]\n\n if main_cell is not None:\n style = main_cell.get(\"style\", \"\")\n\n shapes[title] = {\n \"baseStyle\": style,\n \"width\": w,\n \"height\": h,\n \"xml_class\": \"mxCell\",\n }\n else:\n errors.append(f\"Item {idx} ({title}): No valid mxCell found in XML\")\n\n except ET.ParseError as e:\n errors.append(f\"Item {idx} ({title}): XML parse error - {str(e)}\")\n except Exception as e:\n errors.append(f\"Item {idx} ({title}): Unexpected error - {str(e)}\")\n\n return shapes, errors", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 3280}, "tests/diagram_tests/legend_test.py::98": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_title_object_created", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/base_diagram_test.py::150": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["style_str_from_dict"], "enclosing_function": "test_empty_dict", "extracted_code": "# Source: src/drawpyo/diagram/base_diagram.py\ndef style_str_from_dict(style_dict: Dict[str, Any]) -> str:\n \"\"\"\n This function returns a concatenated style string from a style dictionary.\n This format is:\n baseStyle;attr1=value;attr2=value\n It will concatenate the key:value pairs with the appropriate semicolons and\n equals except for the baseStyle, which it will prepend to the front with no\n equals sign.\n\n Parameters\n ----------\n style_dict : dict\n A dictionary of style:value pairs.\n\n Returns\n -------\n str\n A string with the style_dicts values concatenated correctly.\n\n \"\"\"\n if \"baseStyle\" in style_dict:\n style_str = [style_dict.pop(\"baseStyle\")]\n else:\n style_str = []\n style_str = style_str + [\n \"{0}={1}\".format(att, style)\n for (att, style) in style_dict.items()\n if style != \"\" and style != None\n ]\n return \";\".join(style_str)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 951}, "tests/xml_base_test.py::109": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo", "pytest"], "enclosing_function": "test_xml_ify", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/xml_base_test.py::74": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_basic_close_tag", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/bar_chart_test.py::327": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart", "TextFormat"], "enclosing_function": "test_custom_text_formats", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)\n\n\n# Source: src/drawpyo/diagram/text_format.py\nclass TextFormat(DiagramBase):\n \"\"\"The TextFormat class handles all of the formatting specifically around a text box or label.\"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"TextFormat objects can be initialized with no properties or any of what's listed below:\n\n Keyword Args:\n fontColor (int, optional): The color of the text in the object (#ffffff)\n fontFamily (str, optional): The typeface of the text in the object (see Draw.io for available fonts)\n fontSize (int, optional): The size of the text in the object in points\n align (str, optional): The horizontal alignment of the text in the object ('left', 'center', or 'right')\n verticalAlign (str, optional): The vertical alignment of the text in the object ('top', 'middle', 'bottom')\n textOpacity (int, optional): The opacity of the text in the object\n direction (str, optional): The direction to print the text ('vertical', 'horizontal')\n bold (bool, optional): Whether the text in the object should be bold\n italic (bool, optional): Whether the text in the object should be italic\n underline (bool, optional): Whether the text in the object should be underlined\n labelPosition (str, optional): The position of the object label ('left', 'center', or 'right')\n labelBackgroundColor (str, optional): The background color of the object label (#ffffff)\n labelBorderColor (str, optional): The border color of the object label (#ffffff)\n formattedText (bool, optional): Whether to render the text as HTML formatted or not\n\n \"\"\"\n super().__init__(**kwargs)\n self.fontFamily: Optional[str] = kwargs.get(\"fontFamily\", None)\n self.fontSize: Optional[int] = kwargs.get(\"fontSize\", None)\n self.fontColor: Optional[str] = kwargs.get(\"fontColor\", None)\n self.labelBorderColor: Optional[str] = kwargs.get(\"labelBorderColor\", None)\n self.labelBackgroundColor: Optional[str] = kwargs.get(\n \"labelBackgroundColor\", None\n )\n self.labelPosition: Optional[str] = kwargs.get(\"labelPosition\", None)\n self.textShadow: Optional[Union[int, str]] = kwargs.get(\"textShadow\", None)\n self.textOpacity: Optional[int] = kwargs.get(\"textOpacity\", None)\n self.spacingTop: Optional[int] = kwargs.get(\"spacingTop\", None)\n self.spacingLeft: Optional[int] = kwargs.get(\"spacingLeft\", None)\n self.spacingBottom: Optional[int] = kwargs.get(\"spacingBottom\", None)\n self.spacingRight: Optional[int] = kwargs.get(\"spacingRight\", None)\n self.spacing: Optional[int] = kwargs.get(\"spacing\", None)\n self.align: Optional[str] = kwargs.get(\"align\", None)\n self.verticalAlign: Optional[str] = kwargs.get(\"verticalAlign\", None)\n # These need to be enumerated\n self._direction: Optional[str] = kwargs.get(\"direction\", None)\n # This is actually horizontal. 0 means vertical text, 1 or not present\n # means horizontal\n self.html: Optional[bool] = kwargs.get(\n \"formattedText\", None\n ) # prints in the style string as html\n self.bold: bool = kwargs.get(\"bold\", False)\n self.italic: bool = kwargs.get(\"italic\", False)\n self.underline: bool = kwargs.get(\"underline\", False)\n\n self._style_attributes: list[str] = [\n \"html\",\n \"fontFamily\",\n \"fontStyle\",\n \"fontSize\",\n \"fontColor\",\n \"labelBorderColor\",\n \"labelBackgroundColor\",\n \"labelPosition\",\n \"textShadow\",\n \"textOpacity\",\n \"spacingTop\",\n \"spacingLeft\",\n \"spacingBottom\",\n \"spacingRight\",\n \"spacing\",\n \"align\",\n \"verticalAlign\",\n \"horizontal\",\n ]\n\n def __repr__(self) -> str:\n \"\"\"\n A concise, informative representation for TextFormat.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Font properties\n if self.fontFamily:\n parts.append(f\"fontFamily={self.fontFamily!r}\")\n if self.fontSize:\n parts.append(f\"fontSize={self.fontSize}\")\n if self.fontColor:\n parts.append(f\"fontColor={self.fontColor!r}\")\n\n # Style flags\n flags = []\n if self.bold:\n flags.append(\"bold\")\n if self.italic:\n flags.append(\"italic\")\n if self.underline:\n flags.append(\"underline\")\n if flags:\n parts.append(\"fontStyle=\" + \"|\".join(flags))\n\n # Alignment\n if self.align:\n parts.append(f\"align={self.align!r}\")\n if self.verticalAlign:\n parts.append(f\"verticalAlign={self.verticalAlign!r}\")\n if self._direction:\n parts.append(f\"direction={self._direction!r}\")\n if self.html:\n parts.append(\"formattedText=True\")\n\n # Label styling\n if self.labelPosition:\n parts.append(f\"labelPosition={self.labelPosition!r}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n @property\n def formattedText(self) -> Optional[bool]:\n \"\"\"formattedText wraps the Draw.io style attribute 'html'. This controls whether the text is rendered with HTML attributes or as plain text.\"\"\"\n return self.html\n\n @formattedText.setter\n def formattedText(self, value: Optional[bool]) -> None:\n self.html = value\n\n @formattedText.deleter\n def formattedText(self) -> None:\n self.html = None\n\n # The direction of the text is encoded as 'horizontal' in Draw.io. This is\n # unintuitive so I provided a direction alternate syntax.\n @property\n def horizontal(self) -> Optional[int]:\n return directions[self._direction]\n\n @horizontal.setter\n def horizontal(self, value: Optional[int]) -> None:\n if value in directions_inv.keys():\n self._direction = directions_inv[value]\n else:\n raise ValueError(\"{0} is not an allowed value of horizontal\".format(value))\n\n @property\n def directions(self) -> Dict[Optional[str], Optional[int]]:\n \"\"\"The direction controls the direction of the text and can be either horizontal or vertical.\"\"\"\n return directions\n\n @property\n def direction(self) -> Optional[str]:\n return self._direction\n\n @direction.setter\n def direction(self, value: Optional[str]) -> None:\n if value in directions.keys():\n self._direction = value\n else:\n raise ValueError(\"{0} is not an allowed value of direction\".format(value))\n\n @property\n def font_style(self) -> int:\n \"\"\"The font_style is a numeric format that corresponds to a combination of three other attributes: bold, italic, and underline. Any combination of them can be true.\"\"\"\n bld = self.bold\n ita = self.italic\n unl = self.underline\n\n # 0 = normal\n # 1 = bold\n # 2 = italic\n # 3 = bold and italic\n # 4 = underline\n # 5 = bold and underlined\n # 6 = italic and underlined\n # 7 = bold, italic, and underlined\n\n if not bld and not ita and not unl:\n return 0\n elif bld and not ita and not unl:\n return 1\n elif not bld and ita and not unl:\n return 2\n elif bld and ita and not unl:\n return 3\n elif not bld and not ita and unl:\n return 4\n elif bld and not ita and unl:\n return 5\n elif not bld and ita and unl:\n return 6\n elif bld and ita and unl:\n return 7\n return 0 # fallback (shouldn't be reached)\n\n @property\n def fontStyle(self) -> Optional[int]:\n if self.font_style != 0:\n return self.font_style\n return None", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 23323}, "tests/diagram_tests/object_test.py::227": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_opacity", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/edge_test.py::158": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_entry_exit_offsets", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/import_tests/test_import_drawio.py::69": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_geometry_parsing", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/binary_tree_diagram_test.py::232": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryTreeDiagram"], "enclosing_function": "test_from_dict_basic_structure", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8877}, "tests/diagram_tests/pie_chart_test.py::371": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_group_contains_objects", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/diagram_tests/pie_chart_test.py::293": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart", "TextFormat"], "enclosing_function": "test_custom_text_formats", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"\n\n\n# Source: src/drawpyo/diagram/text_format.py\nclass TextFormat(DiagramBase):\n \"\"\"The TextFormat class handles all of the formatting specifically around a text box or label.\"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"TextFormat objects can be initialized with no properties or any of what's listed below:\n\n Keyword Args:\n fontColor (int, optional): The color of the text in the object (#ffffff)\n fontFamily (str, optional): The typeface of the text in the object (see Draw.io for available fonts)\n fontSize (int, optional): The size of the text in the object in points\n align (str, optional): The horizontal alignment of the text in the object ('left', 'center', or 'right')\n verticalAlign (str, optional): The vertical alignment of the text in the object ('top', 'middle', 'bottom')\n textOpacity (int, optional): The opacity of the text in the object\n direction (str, optional): The direction to print the text ('vertical', 'horizontal')\n bold (bool, optional): Whether the text in the object should be bold\n italic (bool, optional): Whether the text in the object should be italic\n underline (bool, optional): Whether the text in the object should be underlined\n labelPosition (str, optional): The position of the object label ('left', 'center', or 'right')\n labelBackgroundColor (str, optional): The background color of the object label (#ffffff)\n labelBorderColor (str, optional): The border color of the object label (#ffffff)\n formattedText (bool, optional): Whether to render the text as HTML formatted or not\n\n \"\"\"\n super().__init__(**kwargs)\n self.fontFamily: Optional[str] = kwargs.get(\"fontFamily\", None)\n self.fontSize: Optional[int] = kwargs.get(\"fontSize\", None)\n self.fontColor: Optional[str] = kwargs.get(\"fontColor\", None)\n self.labelBorderColor: Optional[str] = kwargs.get(\"labelBorderColor\", None)\n self.labelBackgroundColor: Optional[str] = kwargs.get(\n \"labelBackgroundColor\", None\n )\n self.labelPosition: Optional[str] = kwargs.get(\"labelPosition\", None)\n self.textShadow: Optional[Union[int, str]] = kwargs.get(\"textShadow\", None)\n self.textOpacity: Optional[int] = kwargs.get(\"textOpacity\", None)\n self.spacingTop: Optional[int] = kwargs.get(\"spacingTop\", None)\n self.spacingLeft: Optional[int] = kwargs.get(\"spacingLeft\", None)\n self.spacingBottom: Optional[int] = kwargs.get(\"spacingBottom\", None)\n self.spacingRight: Optional[int] = kwargs.get(\"spacingRight\", None)\n self.spacing: Optional[int] = kwargs.get(\"spacing\", None)\n self.align: Optional[str] = kwargs.get(\"align\", None)\n self.verticalAlign: Optional[str] = kwargs.get(\"verticalAlign\", None)\n # These need to be enumerated\n self._direction: Optional[str] = kwargs.get(\"direction\", None)\n # This is actually horizontal. 0 means vertical text, 1 or not present\n # means horizontal\n self.html: Optional[bool] = kwargs.get(\n \"formattedText\", None\n ) # prints in the style string as html\n self.bold: bool = kwargs.get(\"bold\", False)\n self.italic: bool = kwargs.get(\"italic\", False)\n self.underline: bool = kwargs.get(\"underline\", False)\n\n self._style_attributes: list[str] = [\n \"html\",\n \"fontFamily\",\n \"fontStyle\",\n \"fontSize\",\n \"fontColor\",\n \"labelBorderColor\",\n \"labelBackgroundColor\",\n \"labelPosition\",\n \"textShadow\",\n \"textOpacity\",\n \"spacingTop\",\n \"spacingLeft\",\n \"spacingBottom\",\n \"spacingRight\",\n \"spacing\",\n \"align\",\n \"verticalAlign\",\n \"horizontal\",\n ]\n\n def __repr__(self) -> str:\n \"\"\"\n A concise, informative representation for TextFormat.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Font properties\n if self.fontFamily:\n parts.append(f\"fontFamily={self.fontFamily!r}\")\n if self.fontSize:\n parts.append(f\"fontSize={self.fontSize}\")\n if self.fontColor:\n parts.append(f\"fontColor={self.fontColor!r}\")\n\n # Style flags\n flags = []\n if self.bold:\n flags.append(\"bold\")\n if self.italic:\n flags.append(\"italic\")\n if self.underline:\n flags.append(\"underline\")\n if flags:\n parts.append(\"fontStyle=\" + \"|\".join(flags))\n\n # Alignment\n if self.align:\n parts.append(f\"align={self.align!r}\")\n if self.verticalAlign:\n parts.append(f\"verticalAlign={self.verticalAlign!r}\")\n if self._direction:\n parts.append(f\"direction={self._direction!r}\")\n if self.html:\n parts.append(\"formattedText=True\")\n\n # Label styling\n if self.labelPosition:\n parts.append(f\"labelPosition={self.labelPosition!r}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n @property\n def formattedText(self) -> Optional[bool]:\n \"\"\"formattedText wraps the Draw.io style attribute 'html'. This controls whether the text is rendered with HTML attributes or as plain text.\"\"\"\n return self.html\n\n @formattedText.setter\n def formattedText(self, value: Optional[bool]) -> None:\n self.html = value\n\n @formattedText.deleter\n def formattedText(self) -> None:\n self.html = None\n\n # The direction of the text is encoded as 'horizontal' in Draw.io. This is\n # unintuitive so I provided a direction alternate syntax.\n @property\n def horizontal(self) -> Optional[int]:\n return directions[self._direction]\n\n @horizontal.setter\n def horizontal(self, value: Optional[int]) -> None:\n if value in directions_inv.keys():\n self._direction = directions_inv[value]\n else:\n raise ValueError(\"{0} is not an allowed value of horizontal\".format(value))\n\n @property\n def directions(self) -> Dict[Optional[str], Optional[int]]:\n \"\"\"The direction controls the direction of the text and can be either horizontal or vertical.\"\"\"\n return directions\n\n @property\n def direction(self) -> Optional[str]:\n return self._direction\n\n @direction.setter\n def direction(self, value: Optional[str]) -> None:\n if value in directions.keys():\n self._direction = value\n else:\n raise ValueError(\"{0} is not an allowed value of direction\".format(value))\n\n @property\n def font_style(self) -> int:\n \"\"\"The font_style is a numeric format that corresponds to a combination of three other attributes: bold, italic, and underline. Any combination of them can be true.\"\"\"\n bld = self.bold\n ita = self.italic\n unl = self.underline\n\n # 0 = normal\n # 1 = bold\n # 2 = italic\n # 3 = bold and italic\n # 4 = underline\n # 5 = bold and underlined\n # 6 = italic and underlined\n # 7 = bold, italic, and underlined\n\n if not bld and not ita and not unl:\n return 0\n elif bld and not ita and not unl:\n return 1\n elif not bld and ita and not unl:\n return 2\n elif bld and ita and not unl:\n return 3\n elif not bld and not ita and unl:\n return 4\n elif bld and not ita and unl:\n return 5\n elif not bld and ita and unl:\n return 6\n elif bld and ita and unl:\n return 7\n return 0 # fallback (shouldn't be reached)\n\n @property\n def fontStyle(self) -> Optional[int]:\n if self.font_style != 0:\n return self.font_style\n return None", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 16787}, "tests/diagram_tests/binary_tree_diagram_test.py::100": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject", "BinaryTreeDiagram"], "enclosing_function": "test_add_left_and_add_right_assign_tree", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)\n\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 12864}, "tests/file_test.py::68": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_multiple_pages", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/color_management_test.py::76": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme"], "enclosing_function": "test_hex_strings_normalize_to_uppercase", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/legend_test.py::124": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend", "Object", "StandardColor"], "enclosing_function": "test_background_is_added", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"\n\n\n# Source: src/drawpyo/utils/standard_colors.py\nclass StandardColor(str, Enum):\n NONE = \"none\"\n BLACK = \"#000000\"\n WHITE = \"#FFFFFF\"\n GRAY1 = \"#E6E6E6\"\n GRAY2 = \"#CCCCCC\"\n GRAY3 = \"#B3B3B3\"\n GRAY4 = \"#999999\"\n GRAY5 = \"#808080\"\n GRAY6 = \"#666666\"\n GRAY7 = \"#4D4D4D\"\n GRAY8 = \"#333333\"\n GRAY9 = \"#1A1A1A\"\n RED1 = \"#FFCCCC\"\n RED2 = \"#FF9999\"\n RED3 = \"#FF6666\"\n RED4 = \"#FF3333\"\n RED5 = \"#FF0000\"\n RED6 = \"#CC0000\"\n RED7 = \"#990000\"\n RED8 = \"#660000\"\n RED9 = \"#330000\"\n ORANGE1 = \"#FFE6CC\"\n ORANGE2 = \"#FFCC99\"\n ORANGE3 = \"#FFB366\"\n ORANGE4 = \"#FF9933\"\n ORANGE5 = \"#FF8000\"\n ORANGE6 = \"#CC6600\"\n ORANGE7 = \"#994C00\"\n ORANGE8 = \"#663300\"\n ORANGE9 = \"#331A00\"\n YELLOW1 = \"#FFFFCC\"\n YELLOW2 = \"#FFFF99\"\n YELLOW3 = \"#FFFF66\"\n YELLOW4 = \"#FFFF33\"\n YELLOW5 = \"#FFFF00\"\n YELLOW6 = \"#CCCC00\"\n YELLOW7 = \"#999900\"\n YELLOW8 = \"#666600\"\n YELLOW9 = \"#333300\"\n LIME1 = \"#E6FFCC\"\n LIME2 = \"#CCFF99\"\n LIME3 = \"#B3FF66\"\n LIME4 = \"#99FF33\"\n LIME5 = \"#80FF00\"\n LIME6 = \"#66CC00\"\n LIME7 = \"#4D9900\"\n LIME8 = \"#336600\"\n LIME9 = \"#1A3300\"\n GREEN1 = \"#CCFFCC\"\n GREEN2 = \"#99FF99\"\n GREEN3 = \"#66FF66\"\n GREEN4 = \"#33FF33\"\n GREEN5 = \"#00FF00\"\n GREEN6 = \"#00CC00\"\n GREEN7 = \"#009900\"\n GREEN8 = \"#006600\"\n GREEN9 = \"#003300\"\n EMERALD1 = \"#CCFFE6\"\n EMERALD2 = \"#99FFCC\"\n EMERALD3 = \"#66FFB3\"\n EMERALD4 = \"#33FF99\"\n EMERALD5 = \"#00FF80\"\n EMERALD6 = \"#00CC66\"\n EMERALD7 = \"#00994D\"\n EMERALD8 = \"#006633\"\n EMERALD9 = \"#00331A\"\n CYAN1 = \"#CCFFFF\"\n CYAN2 = \"#99FFFF\"\n CYAN3 = \"#66FFFF\"\n CYAN4 = \"#33FFFF\"\n CYAN5 = \"#00FFFF\"\n CYAN6 = \"#00CCCC\"\n CYAN7 = \"#009999\"\n CYAN8 = \"#006666\"\n CYAN9 = \"#003333\"\n BLUE1 = \"#CCE5FF\"\n BLUE2 = \"#99CCFF\"\n BLUE3 = \"#66B2FF\"\n BLUE4 = \"#3399FF\"\n BLUE5 = \"#007FFF\"\n BLUE6 = \"#0066CC\"\n BLUE7 = \"#004C99\"\n BLUE8 = \"#003366\"\n BLUE9 = \"#001933\"\n INDIGO1 = \"#CCCCFF\"\n INDIGO2 = \"#9999FF\"\n INDIGO3 = \"#6666FF\"\n INDIGO4 = \"#3333FF\"\n INDIGO5 = \"#0000FF\"\n INDIGO6 = \"#0000CC\"\n INDIGO7 = \"#000099\"\n INDIGO8 = \"#000066\"\n INDIGO9 = \"#000033\"\n PURPLE1 = \"#E5CCFF\"\n PURPLE2 = \"#CC99FF\"\n PURPLE3 = \"#B266FF\"\n PURPLE4 = \"#9933FF\"\n PURPLE5 = \"#7F00FF\"\n PURPLE6 = \"#6600CC\"\n PURPLE7 = \"#6600CC\"\n PURPLE8 = \"#330066\"\n PURPLE9 = \"#190033\"\n MAGENTA1 = \"#FFCCFF\"\n MAGENTA2 = \"#FF99CC\"\n MAGENTA3 = \"#FF66CC\"\n MAGENTA4 = \"#FF33FF\"\n MAGENTA5 = \"#FF00FF\"\n MAGENTA6 = \"#CC00CC\"\n MAGENTA7 = \"#990099\"\n MAGENTA8 = \"#660066\"\n MAGENTA9 = \"#330033\"\n CRIMSON1 = \"#FFCCE6\"\n CRIMSON2 = \"#FF99CC\"\n CRIMSON3 = \"#FF66B3\"\n CRIMSON4 = \"#FF3399\"\n CRIMSON5 = \"#FF0080\"\n CRIMSON6 = \"#CC0066\"\n CRIMSON7 = \"#99004D\"\n CRIMSON8 = \"#660033\"\n CRIMSON9 = \"#33001A\"\n\n\n# Source: src/drawpyo/diagram/objects.py\nclass Object(DiagramBase):\n \"\"\"\n The Object class is the base object for all shapes in Draw.io.\n\n More information about objects are in the Usage documents at [Usage - Objects](../../usage/objects).\n \"\"\"\n\n ###########################################################\n # Initialization Functions\n ###########################################################\n\n def __init__(\n self, value: str = \"\", position: Tuple[int, int] = (0, 0), **kwargs: Any\n ) -> None:\n \"\"\"A Object can be initialized with as many or as few of its styling attributes as is desired.\n\n Args:\n value (str, optional): The text to fill the object with. Defaults to \"\".\n position (tuple, optional): The position of the object in pixels, in (X, Y). Defaults to (0, 0).\n\n Keyword Args:\n aspect (optional): Aspect ratio handling. Defaults to None.\n autocontract (bool, optional): Whether to contract to fit the child objects. Defaults to False.\n autosize_margin (int, optional): What margin in pixels to leave around the child objects. Defaults to 20.\n autosize_to_children (bool, optional): Whether to autoexpand when child objects are added. Defaults to False.\n baseStyle (optional): Base style for the object. Defaults to None.\n children (list of Objects, optional): The subobjects to add to this object as a parent. Defaults to [].\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n comic (bool, optional): Add comic styling to the object. Defaults to None.\n fillColor (Union[str, StandardColor], optional): The object fill color. Defaults to None.\n glass (bool, optional): Apply glass styling to the object. Defaults to None.\n height (int, optional): The height of the object in pixels. Defaults to 80.\n in_edges (list, optional): List of incoming edges to this object. Defaults to [].\n line_pattern (str, optional): The stroke style of the object. Defaults to \"solid\".\n opacity (int, optional): The object's opacity, 0-100. Defaults to None.\n out_edges (list, optional): List of outgoing edges from this object. Defaults to [].\n parent (Object, optional): The parent object (container, etc) of this object. Defaults to None.\n position_rel_to_parent (tuple, optional): The position of the object relative to the parent in pixels, in (X, Y).\n rounded (int or bool, optional): Whether to round the corners of the shape. Defaults to 0.\n shadow (bool, optional): Add a shadow to the object. Defaults to None.\n sketch (bool, optional): Add sketch styling to the object. Defaults to None.\n strokeColor (Union[str, StandardColor], optional): The object stroke color. Defaults to None.\n template_object (Object, optional): Another object to copy the style_attributes from. Defaults to None.\n text_format (TextFormat, optional): Formatting specifically around text. Defaults to TextFormat().\n vertex (int, optional): Vertex flag for the object. Defaults to 1.\n whiteSpace (str, optional): White space handling. Defaults to \"wrap\".\n width (int, optional): The width of the object in pixels. Defaults to 120.\n \"\"\"\n super().__init__(**kwargs)\n self._style_attributes: List[str] = [\n \"whiteSpace\",\n \"rounded\",\n \"fillColor\",\n \"strokeColor\",\n \"glass\",\n \"shadow\",\n \"comic\",\n \"sketch\",\n \"opacity\",\n \"dashed\",\n ]\n\n self.geometry: Geometry = Geometry(parent_object=self)\n\n # Subobjecting\n # If there is a parent passed in, disable that parents\n # autoexpanding until position is set\n if \"parent\" in kwargs:\n parent: Object = kwargs.get(\"parent\")\n old_parent_autosize: bool = parent.autosize_to_children\n parent.autoexpand = False\n self.parent: Optional[Object] = parent\n else:\n self._parent: Optional[Object] = None\n self.children: List[Object] = kwargs.get(\"children\", [])\n self.autosize_to_children: bool = kwargs.get(\"autosize_to_children\", False)\n self.autocontract: bool = kwargs.get(\"autocontract\", False)\n self.autosize_margin: int = kwargs.get(\"autosize_margin\", 20)\n\n # Geometry\n self.position: Optional[tuple] = position\n # Since the position is already set to either a passed in arg or the default this will\n # either override that default position or redundantly reset the position to the same value\n self.position_rel_to_parent: Optional[tuple] = kwargs.get(\n \"position_rel_to_parent\", position\n )\n self.width: int = kwargs.get(\"width\", 120)\n self.height: int = kwargs.get(\"height\", 80)\n self.vertex: int = kwargs.get(\"vertex\", 1)\n\n # TODO enumerate to fixed\n self.aspect = kwargs.get(\"aspect\", None)\n\n # Style\n self.baseStyle: Optional[str] = kwargs.get(\"baseStyle\", None)\n\n self.rounded: Optional[bool] = kwargs.get(\"rounded\", 0)\n self.whiteSpace: Optional[str] = kwargs.get(\"whiteSpace\", \"wrap\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"strokeColor\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fillColor\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n self.glass: Optional[bool] = kwargs.get(\"glass\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.comic: Optional[bool] = kwargs.get(\"comic\", None)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.line_pattern: Optional[str] = kwargs.get(\"line_pattern\", \"solid\")\n\n self.out_edges: List[Any] = kwargs.get(\"out_edges\", [])\n self.in_edges: List[Any] = kwargs.get(\"in_edges\", [])\n\n self.xml_class: str = \"mxCell\"\n\n if \"template_object\" in kwargs:\n self.template_object: Object = kwargs.get(\"template_object\")\n self._apply_style_from_template(self.template_object)\n self.width = self.template_object.width\n self.height = self.template_object.height\n\n # Content\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.value: Optional[str] = value\n\n # If a parent was passed in, reactivate the parents autoexpanding and update it\n if \"parent\" in kwargs:\n self.parent.autosize_to_children = old_parent_autosize\n self.update_parent()\n\n logger.debug(f\"🔲 Object created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A more informative representation for debugging.\n \"\"\"\n parts = []\n\n # Geometry\n parts.append(f\"pos: {self.position}\")\n parts.append(f\"size: ({self.width}x{self.height})\")\n\n # Parent info\n if getattr(self, \"parent\", None):\n parts.append(f\"parent: {self.parent.__class__.__name__}\")\n\n # Child count\n if getattr(self, \"children\", None):\n parts.append(f\"children: {len(self.children)}\")\n\n joined = \" | \".join(parts)\n return f\"{self.value} | {joined}\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def __delete__(self) -> None:\n self.page.remove_object(self)\n\n @classmethod\n def create_from_template_object(\n cls,\n template_object: \"Object\",\n value: Optional[str] = None,\n position: Optional[Tuple[int, int]] = None,\n page: Optional[Any] = None,\n ) -> \"Object\":\n \"\"\"Object can be instantiated from another object. This will initialize the Object with the same formatting, then set a new position and value.\n\n Args:\n template_object (Object): Another drawpyo Object to use as a template\n value (str, optional): The text contents of the object. Defaults to None.\n position (tuple, optional): The position where the object should be placed. Defaults to (0, 0).\n page (Page, optional): The Page object to place the object on. Defaults to None.\n\n Returns:\n Object: The newly created object\n \"\"\"\n new_obj: Object = cls(\n value=value,\n page=page,\n width=template_object.width,\n height=template_object.height,\n template_object=template_object,\n )\n if position is not None:\n new_obj.position = position\n if value is not None:\n new_obj.value = value\n return new_obj\n\n @classmethod\n def create_from_style_string(cls, style_string: str) -> \"Object\":\n \"\"\"Objects can be instantiated from a style string. These strings are most easily found in the Draw.io app, by styling an object as desired then right-clicking and selecting \"Edit Style\". Copying that text into this function will generate an object styled the same.\n\n Args:\n style_string (str): A Draw.io generated style string.\n\n Returns:\n Object: An object formatted with the style string\n \"\"\"\n cls.apply_style_from_string(style_string)\n return cls\n\n @classmethod\n def create_from_library(\n cls, library: Union[str, Dict[str, Any]], obj_name: str\n ) -> \"Object\":\n \"\"\"This function generates a Object from a library. The library can either be custom imported from a TOML or the name of one of the built-in Draw.io libraries.\n\n Any keyword arguments that can be passed in to a Object creation can be passed into this function and it will format the base object. However, the styling in the library will overwrite that formatting.\n\n Args:\n library (str or dict): The library containing the object\n obj_name (str): The name of the object in the library to generate\n\n Returns:\n Object: An object with the style from the library\n \"\"\"\n new_obj: Object = cls()\n new_obj.format_as_library_object(library, obj_name)\n return new_obj\n\n def format_as_library_object(\n self, library: Union[str, Dict[str, Any]], obj_name: str\n ) -> None:\n \"\"\"This function applies the style from a library to an existing object. The library can either be custom imported from a TOML or the name of one of the built-in Draw.io libraries.\n\n Args:\n library (str or dict): The library containing the object\n obj_name (str): The name of the object in the library to generate\n\n Raises:\n ValueError: If the library or object name is invalid or not found.\n KeyError: If required keys are missing from the object definition.\n \"\"\"\n if type(library) == str:\n if library in base_libraries:\n library_dict: Dict[str, Any] = base_libraries[library]\n if obj_name in library_dict:\n obj_dict: Dict[str, Any] = library_dict[obj_name]\n self.apply_attribute_dict(obj_dict)\n else:\n raise ValueError(\n f\"Object '{obj_name}' not found in library '{library}'. \"\n f\"Available objects: {', '.join(list(library_dict.keys())[:10])}\"\n + (\"...\" if len(library_dict) > 10 else \"\")\n )\n else:\n raise ValueError(\n f\"Library '{library}' not found in base_libraries. \"\n f\"Available libraries: {', '.join(base_libraries.keys())}\"\n )\n elif type(library) == dict:\n if obj_name not in library:\n raise ValueError(\n f\"Object '{obj_name}' not found in provided library dictionary. \"\n f\"Available objects: {', '.join(list(library.keys())[:10])}\"\n + (\"...\" if len(library) > 10 else \"\")\n )\n obj_dict: Dict[str, Any] = library[obj_name]\n\n # Validate that we have at least some usable data\n if not obj_dict:\n raise ValueError(\n f\"Object '{obj_name}' has no properties defined in the library\"\n )\n\n # Warn if baseStyle is missing (common in mxlibrary shapes)\n if \"baseStyle\" not in obj_dict:\n logger.warning(\n f\"Object '{obj_name}' does not have a 'baseStyle' property. \"\n f\"This may result in a shape without styling.\"\n )\n\n self.apply_attribute_dict(obj_dict)\n else:\n raise ValueError(\n f\"Invalid library type: expected str or dict, got {type(library).__name__}\"\n )\n\n @property\n def attributes(self) -> Dict[str, Any]:\n return {\n \"id\": self.id,\n \"value\": self.value,\n \"style\": self.style,\n \"vertex\": self.vertex,\n \"parent\": self.xml_parent_id,\n }\n\n ###########################################################\n # Style templates\n ###########################################################\n\n @property\n def line_styles(self) -> Dict[str, Any]:\n return line_styles\n\n @property\n def container(self) -> Dict[Optional[str], None]:\n return container\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def line_pattern(self) -> Optional[str]:\n \"\"\"Two properties are enumerated together into line_pattern: dashed and dashPattern. line_pattern simplifies this with an external database that contains the dropdown options from the Draw.io app then outputs the correct combination of dashed and dashPattern.\n\n However in some cases dashed and dashpattern need to be set individually, such as when formatting from a style string. In that case, the setters for those two attributes will disable the other.\n\n Returns:\n str: The line style\n \"\"\"\n return self._line_pattern\n\n @line_pattern.setter\n def line_pattern(self, value: str) -> None:\n if value in line_styles.keys():\n self._line_pattern = value\n else:\n raise ValueError(\n \"{0} is not an allowed value of line_pattern\".format(value)\n )\n\n @property\n def dashed(self) -> Optional[Union[bool, Any]]:\n \"\"\"This is one of the properties that defines the line style. Along with dashPattern, it can be overriden by setting line_pattern or set directly.\n\n Returns:\n str: Whether the object stroke is dashed.\n \"\"\"\n if self._line_pattern is None:\n return self._dashed\n else:\n return line_styles[self._line_pattern]\n\n @dashed.setter\n def dashed(self, value: bool) -> None:\n self._line_pattern = None\n self._dashed = value\n\n @property\n def dashPattern(self) -> Optional[Union[str, Any]]:\n \"\"\"This is one of the properties that defines the line style. Along with dashed, it can be overriden by setting line_pattern or set directly.\n\n Returns:\n str: What style the object stroke is dashed with.\n \"\"\"\n if self._line_pattern is None:\n return self._dashPattern\n else:\n return line_styles[self._line_pattern]\n\n @dashPattern.setter\n def dashPattern(self, value: str) -> None:\n self._line_pattern = None\n self._dashPattern = value\n\n ###########################################################\n # Geometry properties\n ###########################################################\n\n @property\n def width(self) -> int:\n \"\"\"This property makes geometry.width available to the owning class for ease of access.\"\"\"\n return self.geometry.width\n\n @width.setter\n def width(self, value: int) -> None:\n self.geometry.width = value\n self.update_parent()\n\n @property\n def height(self) -> int:\n \"\"\"This property makes geometry.height available to the owning class for ease of access.\"\"\"\n return self.geometry.height\n\n @height.setter\n def height(self, value: int) -> None:\n self.geometry.height = value\n self.update_parent()\n\n # Position property\n @property\n def position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The position of the object on the page. This is the top left corner. It's set with a tuple of ints, X and Y respectively.\n\n (X, Y)\n\n Returns:\n tuple: A tuple of ints describing the top left corner position of the object\n \"\"\"\n if self.parent is not None:\n return (\n self.geometry.x + self.parent.position[0],\n self.geometry.y + self.parent.position[1],\n )\n return (self.geometry.x, self.geometry.y)\n\n @position.setter\n def position(self, value: Tuple[Union[int, float], Union[int, float]]) -> None:\n if self.parent is not None:\n self.geometry.x = value[0] - self.parent.position[0]\n self.geometry.y = value[1] - self.parent.position[1]\n else:\n self.geometry.x = value[0]\n self.geometry.y = value[1]\n self.update_parent()\n\n # Position Rel to Parent\n @property\n def position_rel_to_parent(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The position of the object relative to its parent (container). If there's no parent this will be relative to the page. This is the top left corner. It's set with a tuple of ints, X and Y respectively.\n\n (X, Y)\n\n Returns:\n tuple: A tuple of ints describing the top left corner position of the object\n \"\"\"\n return (self.geometry.x, self.geometry.y)\n\n @position_rel_to_parent.setter\n def position_rel_to_parent(\n self, value: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n self.geometry.x = value[0]\n self.geometry.y = value[1]\n self.update_parent()\n\n @property\n def center_position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The position of the object on the page. This is the center of the object. It's set with a tuple of ints, X and Y respectively.\n\n (X, Y)\n\n Returns:\n tuple: A tuple of ints describing the center position of the object\n \"\"\"\n x: Union[int, float] = self.geometry.x + self.geometry.width / 2\n y: Union[int, float] = self.geometry.y + self.geometry.height / 2\n return (x, y)\n\n @center_position.setter\n def center_position(\n self, position: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n self.geometry.x = position[0] - self.geometry.width / 2\n self.geometry.y = position[1] - self.geometry.height / 2\n\n ###########################################################\n # Subobjects\n ###########################################################\n # TODO add to documentation\n\n @property\n def xml_parent_id(self) -> Union[int, Any]:\n if self.parent is not None:\n return self.parent.id\n return 1\n\n @property\n def parent(self) -> Optional[\"Object\"]:\n \"\"\"The parent object that owns this object. This is usually a container of some kind but can be any other object.\n\n Returns:\n Object: the parent object.\n \"\"\"\n return self._parent\n\n @parent.setter\n def parent(self, value: Optional[\"Object\"]) -> None:\n if isinstance(value, Object):\n # value.add_object(self)\n value.children.append(self)\n self.update_parent()\n self._parent = value\n\n def add_object(self, child_object: \"Object\") -> None:\n \"\"\"Adds a child object to this object, sets the child objects parent, and autoexpands this object if set to.\n\n Args:\n child_object (Object): object to add as a child\n \"\"\"\n child_object._parent = self # Bypass the setter to prevent a loop\n self.children.append(child_object)\n if self.autosize_to_children:\n self.resize_to_children()\n\n def remove_object(self, child_object: \"Object\") -> None:\n \"\"\"Removes a child object from this object, clears the child objects parent, and autoexpands this object if set to.\n\n Args:\n child_object (Object): object to remove as a child\n \"\"\"\n child_object._parent = None # Bypass the setter to prevent a loop\n self.children.remove(child_object)\n if self.autosize_to_children:\n self.resize_to_children()\n\n def update_parent(self) -> None:\n \"\"\"If a parent object is set and the parent is set to autoexpand, then autoexpand it.\"\"\"\n # This function needs to be callable prior to the parent being set during init,\n # hence the hasattr() check.\n if (\n hasattr(self, \"_parent\")\n and self.parent is not None\n and self.parent.autosize_to_children\n ):\n # if the parent is autoexpanding, call the autoexpand function\n self.parent.resize_to_children()\n\n def resize_to_children(self) -> None:\n \"\"\"If the object contains children (is a container, parent, etc) then expand the size and position to fit all of the children.\n\n By default this function will never shrink the size of the object, only expand it. The contract input can be set for that behavior.\n\n Args:\n contract (bool, optional): Contract the parent object to hug the children. Defaults to False.\n \"\"\"\n # Get current extents\n if len(self.children) == 0:\n return\n if self.autocontract:\n topmost: Union[int, float] = 65536\n bottommost: Union[int, float] = -65536\n leftmost: Union[int, float] = 65536\n rightmost: Union[int, float] = -65536\n else:\n topmost: Union[int, float] = self.position[1]\n bottommost: Union[int, float] = self.position[1] + self.height\n leftmost: Union[int, float] = self.position[0]\n rightmost: Union[int, float] = self.position[0] + self.width\n\n # Check all child objects for extents\n for child_object in self.children:\n topmost = min(topmost, child_object.position[1] - self.autosize_margin)\n bottommost = max(\n bottommost,\n child_object.position[1] + child_object.height + self.autosize_margin,\n )\n leftmost = min(leftmost, child_object.position[0] - self.autosize_margin)\n rightmost = max(\n rightmost,\n child_object.position[0] + child_object.width + self.autosize_margin,\n )\n\n # Set self extents to furthest positions\n self.move_wo_children((leftmost, topmost))\n self.width = rightmost - leftmost\n self.height = bottommost - topmost\n\n def move_wo_children(\n self, position: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n \"\"\"Move the parent object relative to the page without moving the children relative to the page.\n\n Args:\n position (Tuple of Ints): The target position for the parent object.\n \"\"\"\n # Disable autoexpand to avoid recursion from child_objects\n # attempting to update their autoexpanding parent upon a move\n old_autoexpand: bool = self.autosize_to_children\n self.autosize_to_children = False\n\n # Move children to counter upcoming parent move\n pos_delta: List[Union[int, float]] = [\n old_pos - new_pos for old_pos, new_pos in zip(self.position, position)\n ]\n for child_object in self.children:\n child_object.position = (\n child_object.position[0] + pos_delta[0],\n child_object.position[1] + pos_delta[1],\n )\n\n # Set new position and re-enable autoexpand\n self.position = position\n self.autosize_to_children = old_autoexpand\n\n ###########################################################\n # Edge Tracking\n ###########################################################\n\n def add_out_edge(self, edge: Any) -> None:\n \"\"\"Add an edge out of the object. If an edge is created with this object set as the source this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object originating at this object\n \"\"\"\n self.out_edges.append(edge)\n\n def remove_out_edge(self, edge: Any) -> None:\n \"\"\"Remove an edge out of the object. If an edge linked to this object has the source changed or removed this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object originating at this object\n \"\"\"\n self.out_edges.remove(edge)\n\n def add_in_edge(self, edge: Any) -> None:\n \"\"\"Add an edge into the object. If an edge is created with this object set as the target this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object ending at this object\n \"\"\"\n self.in_edges.append(edge)\n\n def remove_in_edge(self, edge: Any) -> None:\n \"\"\"Remove an edge into the object. If an edge linked to this object has the target changed or removed this function will be called automatically.\n\n Args:\n edge (Edge): An Edge object ending at this object\n \"\"\"\n self.in_edges.remove(edge)\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def xml(self) -> str:\n \"\"\"\n Returns the XML object for the Object: the opening tag with the style attributes, the value, and the closing tag.\n\n Example:\n Text in object\n\n Returns:\n str: A single XML tag containing the object name, style attributes, and a closer.\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 36509}, "tests/import_tests/test_import_drawio.py::37": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_diagram_loads", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/base_diagram_test.py::214": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["drawpyo"], "enclosing_function": "test_geometry_init_default", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/import_tests/test_import_drawio.py::83": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_no_edges", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/object_test.py::140": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_template_chain", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/pie_chart_test.py::451": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_multiple_updates", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/diagram_tests/edge_test.py::159": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_entry_exit_offsets", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/diagram_tests/base_diagram_test.py::80": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["width_input_check"], "enclosing_function": "test_valid_width", "extracted_code": "# Source: src/drawpyo/diagram/base_diagram.py\ndef width_input_check(width: Optional[Union[int, str]]) -> Optional[int]:\n if not width or (isinstance(width, str) and not width.isdigit()):\n return None\n\n width = int(width)\n if width < 1:\n return 1\n elif width > 999:\n return 999\n else:\n return width", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 340}, "tests/diagram_tests/legend_test.py::140": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_standard_color_box", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/bar_chart_test.py::229": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_axis_enabled", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/color_management_test.py::206": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": [], "enclosing_function": "test_hierarchy_defaults_used_when_both_missing", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/xml_base_test.py::138": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_translate_txt_empty_string", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/base_diagram_test.py::82": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["width_input_check"], "enclosing_function": "test_valid_width", "extracted_code": "# Source: src/drawpyo/diagram/base_diagram.py\ndef width_input_check(width: Optional[Union[int, str]]) -> Optional[int]:\n if not width or (isinstance(width, str) and not width.isdigit()):\n return None\n\n width = int(width)\n if width < 1:\n return 1\n elif width > 999:\n return 999\n else:\n return width", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 340}, "tests/import_tests/test_import_drawio.py::70": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_geometry_parsing", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/xml_base_test.py::18": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/xml_base_test.py::133": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_translate_txt_multiple_occurrences", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/legend_test.py::102": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_title_object_created", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/page_test.py::27": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_grid_settings", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/import_tests/test_mxlibrary_import.py::35": {"resolved_imports": ["src/drawpyo/drawio_import/mxlibrary_parser.py", "src/drawpyo/__init__.py"], "used_names": ["parse_mxlibrary"], "enclosing_function": "test_parse_mxlibrary_parsed_correctly", "extracted_code": "# Source: src/drawpyo/drawio_import/mxlibrary_parser.py\ndef parse_mxlibrary(content: str) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:\n \"\"\"\n Parses an mxlibrary file content and extracts shape definitions.\n\n Args:\n content: The string content of the mxlibrary file.\n\n Returns:\n A tuple of (shapes_dict, errors_list) where:\n - shapes_dict: Dictionary with keys as titles and values as dicts containing\n properties like baseStyle, width, height, and xml_class.\n - errors_list: List of error messages for shapes that couldn't be parsed.\n \"\"\"\n errors: List[str] = []\n clean_content = (\n content.replace(\"\", \"\").replace(\"\", \"\").strip()\n )\n\n try:\n data = json.loads(clean_content)\n except json.JSONDecodeError as e:\n # Try to extract JSON array from content\n start = content.find(\"[\")\n end = content.rfind(\"]\")\n if start != -1 and end != -1:\n try:\n data = json.loads(content[start : end + 1])\n except json.JSONDecodeError:\n errors.append(f\"Failed to parse JSON content: {str(e)}\")\n return {}, errors\n else:\n errors.append(f\"No valid JSON array found in content: {str(e)}\")\n return {}, errors\n\n shapes: Dict[str, Dict[str, Any]] = {}\n\n if not isinstance(data, list):\n errors.append(f\"Expected JSON array, got {type(data).__name__}\")\n return {}, errors\n\n for idx, item in enumerate(data):\n if not isinstance(item, dict):\n errors.append(f\"Item {idx}: Expected dict, got {type(item).__name__}\")\n continue\n\n title = item.get(\"title\", \"Untitled\")\n w = item.get(\"w\", 0)\n h = item.get(\"h\", 0)\n xml_encoded = item.get(\"xml\")\n\n if not xml_encoded:\n errors.append(f\"Item {idx} ({title}): Missing 'xml' field\")\n continue\n\n xml_str = html.unescape(xml_encoded)\n\n try:\n try:\n root_element = ET.fromstring(xml_str)\n except ET.ParseError:\n root_element = ET.fromstring(f\"{xml_str}\")\n\n main_cell = None\n cells = []\n\n if root_element.tag == \"mxCell\":\n cells.append(root_element)\n\n for cell in root_element.iter(\"mxCell\"):\n cells.append(cell)\n\n for cell in cells:\n if cell.get(\"vertex\") == \"1\":\n main_cell = cell\n break\n\n if main_cell is None and cells:\n main_cell = cells[0]\n\n if main_cell is not None:\n style = main_cell.get(\"style\", \"\")\n\n shapes[title] = {\n \"baseStyle\": style,\n \"width\": w,\n \"height\": h,\n \"xml_class\": \"mxCell\",\n }\n else:\n errors.append(f\"Item {idx} ({title}): No valid mxCell found in XML\")\n\n except ET.ParseError as e:\n errors.append(f\"Item {idx} ({title}): XML parse error - {str(e)}\")\n except Exception as e:\n errors.append(f\"Item {idx} ({title}): Unexpected error - {str(e)}\")\n\n return shapes, errors", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 3280}, "tests/diagram_tests/edge_test.py::157": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_entry_exit_offsets", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/diagram_tests/object_test.py::37": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/page_test.py::149": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_multiple_objects", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/object_test.py::150": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_fill_color", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/binary_tree_diagram_test.py::262": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryTreeDiagram"], "enclosing_function": "test_from_dict_nested_structure", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8877}, "tests/xml_base_test.py::83": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_open_tag_with_multiple_attributes", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/object_test.py::194": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_width_update", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/import_tests/test_import_drawio.py::54": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_get_by_id", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/xml_base_test.py::128": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_translate_txt_no_replacements", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/object_test.py::247": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_parent_child_relationship", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/bar_chart_test.py::435": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_multiple_updates", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/file_test.py::50": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_page_basic", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/import_tests/test_mxlibrary_import.py::63": {"resolved_imports": ["src/drawpyo/drawio_import/mxlibrary_parser.py", "src/drawpyo/__init__.py"], "used_names": ["load_mxlibrary"], "enclosing_function": "test_load_mxlibrary_from_local_file", "extracted_code": "# Source: src/drawpyo/drawio_import/mxlibrary_parser.py\ndef load_mxlibrary(file_path_or_url: str) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n Loads an mxlibrary from a file path or URL and parses it.\n\n Args:\n file_path_or_url: Local file path or HTTP/HTTPS URL.\n\n Returns:\n Dictionary of shapes.\n\n Raises:\n ValueError: If the file/URL cannot be loaded or parsed.\n FileNotFoundError: If the local file doesn't exist.\n urllib.error.URLError: If the URL cannot be accessed.\n \"\"\"\n content = \"\"\n\n try:\n if file_path_or_url.lower().startswith((\"http://\", \"https://\")):\n try:\n with urllib.request.urlopen(file_path_or_url, timeout=30) as response:\n content = response.read().decode(\"utf-8\")\n except urllib.error.HTTPError as e:\n raise ValueError(\n f\"Failed to fetch mxlibrary from URL '{file_path_or_url}': \"\n f\"HTTP {e.code} - {e.reason}\"\n ) from e\n except urllib.error.URLError as e:\n raise ValueError(\n f\"Failed to access URL '{file_path_or_url}': {str(e.reason)}\"\n ) from e\n except Exception as e:\n raise ValueError(\n f\"Unexpected error fetching URL '{file_path_or_url}': {str(e)}\"\n ) from e\n else:\n try:\n with open(file_path_or_url, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n except FileNotFoundError:\n raise FileNotFoundError(\n f\"mxlibrary file not found: '{file_path_or_url}'\"\n )\n except PermissionError:\n raise ValueError(\n f\"Permission denied reading file: '{file_path_or_url}'\"\n )\n except Exception as e:\n raise ValueError(\n f\"Error reading file '{file_path_or_url}': {str(e)}\"\n ) from e\n\n shapes, errors = parse_mxlibrary(content)\n\n if errors:\n logger.warning(\n f\"Encountered {len(errors)} error(s) while parsing mxlibrary \"\n f\"from '{file_path_or_url}': {'; '.join(errors[:5])}\"\n + (\" ...\" if len(errors) > 5 else \"\")\n )\n\n if not shapes:\n logger.warning(\n f\"No valid shapes found in mxlibrary '{file_path_or_url}'. \"\n f\"Errors: {'; '.join(errors)}\"\n )\n return {}\n\n return shapes\n\n except (ValueError, FileNotFoundError) as e:\n # Re-raise our custom errors\n raise\n except Exception as e:\n # Catch any unexpected errors\n raise ValueError(\n f\"Unexpected error loading mxlibrary from '{file_path_or_url}': {str(e)}\"\n ) from e", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 2877}, "tests/diagram_tests/edge_test.py::142": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_entry_exit_points", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/file_test.py::20": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["Path", "drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/page_test.py::23": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_viewport_settings", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/base_diagram_test.py::213": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["drawpyo"], "enclosing_function": "test_geometry_init_default", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/xml_base_test.py::17": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/page_test.py::57": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_special_features", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/bar_chart_test.py::300": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_calculate_scale_equal_values", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/object_test.py::208": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_stroke_width", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/edge_test.py::24": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_default_values", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/xml_base_test.py::36": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_custom_xml_parent", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/binary_tree_diagram_test.py::159": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject"], "enclosing_function": "test_replace_right_then_left_positions", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4036}, "tests/diagram_tests/pie_chart_test.py::330": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_custom_size", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/file_test.py::49": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_page_basic", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/pie_chart_test.py::496": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_label_offset_constant", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/diagram_tests/binary_tree_diagram_test.py::156": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject"], "enclosing_function": "test_replace_right_then_left_positions", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4036}, "tests/diagram_tests/object_test.py::170": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["StandardColor", "drawpyo"], "enclosing_function": "test_standard_color_enum", "extracted_code": "# Source: src/drawpyo/utils/standard_colors.py\nclass StandardColor(str, Enum):\n NONE = \"none\"\n BLACK = \"#000000\"\n WHITE = \"#FFFFFF\"\n GRAY1 = \"#E6E6E6\"\n GRAY2 = \"#CCCCCC\"\n GRAY3 = \"#B3B3B3\"\n GRAY4 = \"#999999\"\n GRAY5 = \"#808080\"\n GRAY6 = \"#666666\"\n GRAY7 = \"#4D4D4D\"\n GRAY8 = \"#333333\"\n GRAY9 = \"#1A1A1A\"\n RED1 = \"#FFCCCC\"\n RED2 = \"#FF9999\"\n RED3 = \"#FF6666\"\n RED4 = \"#FF3333\"\n RED5 = \"#FF0000\"\n RED6 = \"#CC0000\"\n RED7 = \"#990000\"\n RED8 = \"#660000\"\n RED9 = \"#330000\"\n ORANGE1 = \"#FFE6CC\"\n ORANGE2 = \"#FFCC99\"\n ORANGE3 = \"#FFB366\"\n ORANGE4 = \"#FF9933\"\n ORANGE5 = \"#FF8000\"\n ORANGE6 = \"#CC6600\"\n ORANGE7 = \"#994C00\"\n ORANGE8 = \"#663300\"\n ORANGE9 = \"#331A00\"\n YELLOW1 = \"#FFFFCC\"\n YELLOW2 = \"#FFFF99\"\n YELLOW3 = \"#FFFF66\"\n YELLOW4 = \"#FFFF33\"\n YELLOW5 = \"#FFFF00\"\n YELLOW6 = \"#CCCC00\"\n YELLOW7 = \"#999900\"\n YELLOW8 = \"#666600\"\n YELLOW9 = \"#333300\"\n LIME1 = \"#E6FFCC\"\n LIME2 = \"#CCFF99\"\n LIME3 = \"#B3FF66\"\n LIME4 = \"#99FF33\"\n LIME5 = \"#80FF00\"\n LIME6 = \"#66CC00\"\n LIME7 = \"#4D9900\"\n LIME8 = \"#336600\"\n LIME9 = \"#1A3300\"\n GREEN1 = \"#CCFFCC\"\n GREEN2 = \"#99FF99\"\n GREEN3 = \"#66FF66\"\n GREEN4 = \"#33FF33\"\n GREEN5 = \"#00FF00\"\n GREEN6 = \"#00CC00\"\n GREEN7 = \"#009900\"\n GREEN8 = \"#006600\"\n GREEN9 = \"#003300\"\n EMERALD1 = \"#CCFFE6\"\n EMERALD2 = \"#99FFCC\"\n EMERALD3 = \"#66FFB3\"\n EMERALD4 = \"#33FF99\"\n EMERALD5 = \"#00FF80\"\n EMERALD6 = \"#00CC66\"\n EMERALD7 = \"#00994D\"\n EMERALD8 = \"#006633\"\n EMERALD9 = \"#00331A\"\n CYAN1 = \"#CCFFFF\"\n CYAN2 = \"#99FFFF\"\n CYAN3 = \"#66FFFF\"\n CYAN4 = \"#33FFFF\"\n CYAN5 = \"#00FFFF\"\n CYAN6 = \"#00CCCC\"\n CYAN7 = \"#009999\"\n CYAN8 = \"#006666\"\n CYAN9 = \"#003333\"\n BLUE1 = \"#CCE5FF\"\n BLUE2 = \"#99CCFF\"\n BLUE3 = \"#66B2FF\"\n BLUE4 = \"#3399FF\"\n BLUE5 = \"#007FFF\"\n BLUE6 = \"#0066CC\"\n BLUE7 = \"#004C99\"\n BLUE8 = \"#003366\"\n BLUE9 = \"#001933\"\n INDIGO1 = \"#CCCCFF\"\n INDIGO2 = \"#9999FF\"\n INDIGO3 = \"#6666FF\"\n INDIGO4 = \"#3333FF\"\n INDIGO5 = \"#0000FF\"\n INDIGO6 = \"#0000CC\"\n INDIGO7 = \"#000099\"\n INDIGO8 = \"#000066\"\n INDIGO9 = \"#000033\"\n PURPLE1 = \"#E5CCFF\"\n PURPLE2 = \"#CC99FF\"\n PURPLE3 = \"#B266FF\"\n PURPLE4 = \"#9933FF\"\n PURPLE5 = \"#7F00FF\"\n PURPLE6 = \"#6600CC\"\n PURPLE7 = \"#6600CC\"\n PURPLE8 = \"#330066\"\n PURPLE9 = \"#190033\"\n MAGENTA1 = \"#FFCCFF\"\n MAGENTA2 = \"#FF99CC\"\n MAGENTA3 = \"#FF66CC\"\n MAGENTA4 = \"#FF33FF\"\n MAGENTA5 = \"#FF00FF\"\n MAGENTA6 = \"#CC00CC\"\n MAGENTA7 = \"#990099\"\n MAGENTA8 = \"#660066\"\n MAGENTA9 = \"#330033\"\n CRIMSON1 = \"#FFCCE6\"\n CRIMSON2 = \"#FF99CC\"\n CRIMSON3 = \"#FF66B3\"\n CRIMSON4 = \"#FF3399\"\n CRIMSON5 = \"#FF0080\"\n CRIMSON6 = \"#CC0066\"\n CRIMSON7 = \"#99004D\"\n CRIMSON8 = \"#660033\"\n CRIMSON9 = \"#33001A\"", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2867}, "tests/diagram_tests/color_management_test.py::192": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme"], "enclosing_function": "test_hierarchy_object_specific_over_scheme", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/edge_test.py::143": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_entry_exit_points", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/diagram_tests/color_management_test.py::199": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme"], "enclosing_function": "test_hierarchy_scheme_used_when_object_specific_missing", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/binary_tree_diagram_test.py::258": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryTreeDiagram"], "enclosing_function": "test_from_dict_nested_structure", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8877}, "tests/diagram_tests/pie_chart_test.py::91": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_negative_values", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/page_test.py::53": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_page_size_presets", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/color_management_test.py::20": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme", "pytest"], "enclosing_function": "test_is_valid_hex_accepts_valid_hex", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/bar_chart_test.py::239": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_zero_tick_count", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/diagram_tests/legend_test.py::78": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_repr", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/color_management_test.py::36": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme", "pytest"], "enclosing_function": "test_is_valid_hex_rejects_invalid_hex_strings", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/import_tests/test_import_drawio.py::65": {"resolved_imports": ["src/drawpyo/drawio_import/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/diagram/objects.py"], "used_names": [], "enclosing_function": "test_geometry_parsing", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/pie_chart_test.py::294": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart", "TextFormat"], "enclosing_function": "test_custom_text_formats", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"\n\n\n# Source: src/drawpyo/diagram/text_format.py\nclass TextFormat(DiagramBase):\n \"\"\"The TextFormat class handles all of the formatting specifically around a text box or label.\"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"TextFormat objects can be initialized with no properties or any of what's listed below:\n\n Keyword Args:\n fontColor (int, optional): The color of the text in the object (#ffffff)\n fontFamily (str, optional): The typeface of the text in the object (see Draw.io for available fonts)\n fontSize (int, optional): The size of the text in the object in points\n align (str, optional): The horizontal alignment of the text in the object ('left', 'center', or 'right')\n verticalAlign (str, optional): The vertical alignment of the text in the object ('top', 'middle', 'bottom')\n textOpacity (int, optional): The opacity of the text in the object\n direction (str, optional): The direction to print the text ('vertical', 'horizontal')\n bold (bool, optional): Whether the text in the object should be bold\n italic (bool, optional): Whether the text in the object should be italic\n underline (bool, optional): Whether the text in the object should be underlined\n labelPosition (str, optional): The position of the object label ('left', 'center', or 'right')\n labelBackgroundColor (str, optional): The background color of the object label (#ffffff)\n labelBorderColor (str, optional): The border color of the object label (#ffffff)\n formattedText (bool, optional): Whether to render the text as HTML formatted or not\n\n \"\"\"\n super().__init__(**kwargs)\n self.fontFamily: Optional[str] = kwargs.get(\"fontFamily\", None)\n self.fontSize: Optional[int] = kwargs.get(\"fontSize\", None)\n self.fontColor: Optional[str] = kwargs.get(\"fontColor\", None)\n self.labelBorderColor: Optional[str] = kwargs.get(\"labelBorderColor\", None)\n self.labelBackgroundColor: Optional[str] = kwargs.get(\n \"labelBackgroundColor\", None\n )\n self.labelPosition: Optional[str] = kwargs.get(\"labelPosition\", None)\n self.textShadow: Optional[Union[int, str]] = kwargs.get(\"textShadow\", None)\n self.textOpacity: Optional[int] = kwargs.get(\"textOpacity\", None)\n self.spacingTop: Optional[int] = kwargs.get(\"spacingTop\", None)\n self.spacingLeft: Optional[int] = kwargs.get(\"spacingLeft\", None)\n self.spacingBottom: Optional[int] = kwargs.get(\"spacingBottom\", None)\n self.spacingRight: Optional[int] = kwargs.get(\"spacingRight\", None)\n self.spacing: Optional[int] = kwargs.get(\"spacing\", None)\n self.align: Optional[str] = kwargs.get(\"align\", None)\n self.verticalAlign: Optional[str] = kwargs.get(\"verticalAlign\", None)\n # These need to be enumerated\n self._direction: Optional[str] = kwargs.get(\"direction\", None)\n # This is actually horizontal. 0 means vertical text, 1 or not present\n # means horizontal\n self.html: Optional[bool] = kwargs.get(\n \"formattedText\", None\n ) # prints in the style string as html\n self.bold: bool = kwargs.get(\"bold\", False)\n self.italic: bool = kwargs.get(\"italic\", False)\n self.underline: bool = kwargs.get(\"underline\", False)\n\n self._style_attributes: list[str] = [\n \"html\",\n \"fontFamily\",\n \"fontStyle\",\n \"fontSize\",\n \"fontColor\",\n \"labelBorderColor\",\n \"labelBackgroundColor\",\n \"labelPosition\",\n \"textShadow\",\n \"textOpacity\",\n \"spacingTop\",\n \"spacingLeft\",\n \"spacingBottom\",\n \"spacingRight\",\n \"spacing\",\n \"align\",\n \"verticalAlign\",\n \"horizontal\",\n ]\n\n def __repr__(self) -> str:\n \"\"\"\n A concise, informative representation for TextFormat.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Font properties\n if self.fontFamily:\n parts.append(f\"fontFamily={self.fontFamily!r}\")\n if self.fontSize:\n parts.append(f\"fontSize={self.fontSize}\")\n if self.fontColor:\n parts.append(f\"fontColor={self.fontColor!r}\")\n\n # Style flags\n flags = []\n if self.bold:\n flags.append(\"bold\")\n if self.italic:\n flags.append(\"italic\")\n if self.underline:\n flags.append(\"underline\")\n if flags:\n parts.append(\"fontStyle=\" + \"|\".join(flags))\n\n # Alignment\n if self.align:\n parts.append(f\"align={self.align!r}\")\n if self.verticalAlign:\n parts.append(f\"verticalAlign={self.verticalAlign!r}\")\n if self._direction:\n parts.append(f\"direction={self._direction!r}\")\n if self.html:\n parts.append(\"formattedText=True\")\n\n # Label styling\n if self.labelPosition:\n parts.append(f\"labelPosition={self.labelPosition!r}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n @property\n def formattedText(self) -> Optional[bool]:\n \"\"\"formattedText wraps the Draw.io style attribute 'html'. This controls whether the text is rendered with HTML attributes or as plain text.\"\"\"\n return self.html\n\n @formattedText.setter\n def formattedText(self, value: Optional[bool]) -> None:\n self.html = value\n\n @formattedText.deleter\n def formattedText(self) -> None:\n self.html = None\n\n # The direction of the text is encoded as 'horizontal' in Draw.io. This is\n # unintuitive so I provided a direction alternate syntax.\n @property\n def horizontal(self) -> Optional[int]:\n return directions[self._direction]\n\n @horizontal.setter\n def horizontal(self, value: Optional[int]) -> None:\n if value in directions_inv.keys():\n self._direction = directions_inv[value]\n else:\n raise ValueError(\"{0} is not an allowed value of horizontal\".format(value))\n\n @property\n def directions(self) -> Dict[Optional[str], Optional[int]]:\n \"\"\"The direction controls the direction of the text and can be either horizontal or vertical.\"\"\"\n return directions\n\n @property\n def direction(self) -> Optional[str]:\n return self._direction\n\n @direction.setter\n def direction(self, value: Optional[str]) -> None:\n if value in directions.keys():\n self._direction = value\n else:\n raise ValueError(\"{0} is not an allowed value of direction\".format(value))\n\n @property\n def font_style(self) -> int:\n \"\"\"The font_style is a numeric format that corresponds to a combination of three other attributes: bold, italic, and underline. Any combination of them can be true.\"\"\"\n bld = self.bold\n ita = self.italic\n unl = self.underline\n\n # 0 = normal\n # 1 = bold\n # 2 = italic\n # 3 = bold and italic\n # 4 = underline\n # 5 = bold and underlined\n # 6 = italic and underlined\n # 7 = bold, italic, and underlined\n\n if not bld and not ita and not unl:\n return 0\n elif bld and not ita and not unl:\n return 1\n elif not bld and ita and not unl:\n return 2\n elif bld and ita and not unl:\n return 3\n elif not bld and not ita and unl:\n return 4\n elif bld and not ita and unl:\n return 5\n elif not bld and ita and unl:\n return 6\n elif bld and ita and unl:\n return 7\n return 0 # fallback (shouldn't be reached)\n\n @property\n def fontStyle(self) -> Optional[int]:\n if self.font_style != 0:\n return self.font_style\n return None", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 16787}, "tests/diagram_tests/color_management_test.py::66": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme", "StandardColor"], "enclosing_function": "test_enum_allowed_in_setters", "extracted_code": "# Source: src/drawpyo/utils/standard_colors.py\nclass StandardColor(str, Enum):\n NONE = \"none\"\n BLACK = \"#000000\"\n WHITE = \"#FFFFFF\"\n GRAY1 = \"#E6E6E6\"\n GRAY2 = \"#CCCCCC\"\n GRAY3 = \"#B3B3B3\"\n GRAY4 = \"#999999\"\n GRAY5 = \"#808080\"\n GRAY6 = \"#666666\"\n GRAY7 = \"#4D4D4D\"\n GRAY8 = \"#333333\"\n GRAY9 = \"#1A1A1A\"\n RED1 = \"#FFCCCC\"\n RED2 = \"#FF9999\"\n RED3 = \"#FF6666\"\n RED4 = \"#FF3333\"\n RED5 = \"#FF0000\"\n RED6 = \"#CC0000\"\n RED7 = \"#990000\"\n RED8 = \"#660000\"\n RED9 = \"#330000\"\n ORANGE1 = \"#FFE6CC\"\n ORANGE2 = \"#FFCC99\"\n ORANGE3 = \"#FFB366\"\n ORANGE4 = \"#FF9933\"\n ORANGE5 = \"#FF8000\"\n ORANGE6 = \"#CC6600\"\n ORANGE7 = \"#994C00\"\n ORANGE8 = \"#663300\"\n ORANGE9 = \"#331A00\"\n YELLOW1 = \"#FFFFCC\"\n YELLOW2 = \"#FFFF99\"\n YELLOW3 = \"#FFFF66\"\n YELLOW4 = \"#FFFF33\"\n YELLOW5 = \"#FFFF00\"\n YELLOW6 = \"#CCCC00\"\n YELLOW7 = \"#999900\"\n YELLOW8 = \"#666600\"\n YELLOW9 = \"#333300\"\n LIME1 = \"#E6FFCC\"\n LIME2 = \"#CCFF99\"\n LIME3 = \"#B3FF66\"\n LIME4 = \"#99FF33\"\n LIME5 = \"#80FF00\"\n LIME6 = \"#66CC00\"\n LIME7 = \"#4D9900\"\n LIME8 = \"#336600\"\n LIME9 = \"#1A3300\"\n GREEN1 = \"#CCFFCC\"\n GREEN2 = \"#99FF99\"\n GREEN3 = \"#66FF66\"\n GREEN4 = \"#33FF33\"\n GREEN5 = \"#00FF00\"\n GREEN6 = \"#00CC00\"\n GREEN7 = \"#009900\"\n GREEN8 = \"#006600\"\n GREEN9 = \"#003300\"\n EMERALD1 = \"#CCFFE6\"\n EMERALD2 = \"#99FFCC\"\n EMERALD3 = \"#66FFB3\"\n EMERALD4 = \"#33FF99\"\n EMERALD5 = \"#00FF80\"\n EMERALD6 = \"#00CC66\"\n EMERALD7 = \"#00994D\"\n EMERALD8 = \"#006633\"\n EMERALD9 = \"#00331A\"\n CYAN1 = \"#CCFFFF\"\n CYAN2 = \"#99FFFF\"\n CYAN3 = \"#66FFFF\"\n CYAN4 = \"#33FFFF\"\n CYAN5 = \"#00FFFF\"\n CYAN6 = \"#00CCCC\"\n CYAN7 = \"#009999\"\n CYAN8 = \"#006666\"\n CYAN9 = \"#003333\"\n BLUE1 = \"#CCE5FF\"\n BLUE2 = \"#99CCFF\"\n BLUE3 = \"#66B2FF\"\n BLUE4 = \"#3399FF\"\n BLUE5 = \"#007FFF\"\n BLUE6 = \"#0066CC\"\n BLUE7 = \"#004C99\"\n BLUE8 = \"#003366\"\n BLUE9 = \"#001933\"\n INDIGO1 = \"#CCCCFF\"\n INDIGO2 = \"#9999FF\"\n INDIGO3 = \"#6666FF\"\n INDIGO4 = \"#3333FF\"\n INDIGO5 = \"#0000FF\"\n INDIGO6 = \"#0000CC\"\n INDIGO7 = \"#000099\"\n INDIGO8 = \"#000066\"\n INDIGO9 = \"#000033\"\n PURPLE1 = \"#E5CCFF\"\n PURPLE2 = \"#CC99FF\"\n PURPLE3 = \"#B266FF\"\n PURPLE4 = \"#9933FF\"\n PURPLE5 = \"#7F00FF\"\n PURPLE6 = \"#6600CC\"\n PURPLE7 = \"#6600CC\"\n PURPLE8 = \"#330066\"\n PURPLE9 = \"#190033\"\n MAGENTA1 = \"#FFCCFF\"\n MAGENTA2 = \"#FF99CC\"\n MAGENTA3 = \"#FF66CC\"\n MAGENTA4 = \"#FF33FF\"\n MAGENTA5 = \"#FF00FF\"\n MAGENTA6 = \"#CC00CC\"\n MAGENTA7 = \"#990099\"\n MAGENTA8 = \"#660066\"\n MAGENTA9 = \"#330033\"\n CRIMSON1 = \"#FFCCE6\"\n CRIMSON2 = \"#FF99CC\"\n CRIMSON3 = \"#FF66B3\"\n CRIMSON4 = \"#FF3399\"\n CRIMSON5 = \"#FF0080\"\n CRIMSON6 = \"#CC0066\"\n CRIMSON7 = \"#99004D\"\n CRIMSON8 = \"#660033\"\n CRIMSON9 = \"#33001A\"\n\n\n# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 5549}, "tests/import_tests/test_mxlibrary_import.py::71": {"resolved_imports": ["src/drawpyo/drawio_import/mxlibrary_parser.py", "src/drawpyo/__init__.py"], "used_names": ["load_mxlibrary"], "enclosing_function": "test_load_mxlibrary_from_local_file", "extracted_code": "# Source: src/drawpyo/drawio_import/mxlibrary_parser.py\ndef load_mxlibrary(file_path_or_url: str) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n Loads an mxlibrary from a file path or URL and parses it.\n\n Args:\n file_path_or_url: Local file path or HTTP/HTTPS URL.\n\n Returns:\n Dictionary of shapes.\n\n Raises:\n ValueError: If the file/URL cannot be loaded or parsed.\n FileNotFoundError: If the local file doesn't exist.\n urllib.error.URLError: If the URL cannot be accessed.\n \"\"\"\n content = \"\"\n\n try:\n if file_path_or_url.lower().startswith((\"http://\", \"https://\")):\n try:\n with urllib.request.urlopen(file_path_or_url, timeout=30) as response:\n content = response.read().decode(\"utf-8\")\n except urllib.error.HTTPError as e:\n raise ValueError(\n f\"Failed to fetch mxlibrary from URL '{file_path_or_url}': \"\n f\"HTTP {e.code} - {e.reason}\"\n ) from e\n except urllib.error.URLError as e:\n raise ValueError(\n f\"Failed to access URL '{file_path_or_url}': {str(e.reason)}\"\n ) from e\n except Exception as e:\n raise ValueError(\n f\"Unexpected error fetching URL '{file_path_or_url}': {str(e)}\"\n ) from e\n else:\n try:\n with open(file_path_or_url, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n except FileNotFoundError:\n raise FileNotFoundError(\n f\"mxlibrary file not found: '{file_path_or_url}'\"\n )\n except PermissionError:\n raise ValueError(\n f\"Permission denied reading file: '{file_path_or_url}'\"\n )\n except Exception as e:\n raise ValueError(\n f\"Error reading file '{file_path_or_url}': {str(e)}\"\n ) from e\n\n shapes, errors = parse_mxlibrary(content)\n\n if errors:\n logger.warning(\n f\"Encountered {len(errors)} error(s) while parsing mxlibrary \"\n f\"from '{file_path_or_url}': {'; '.join(errors[:5])}\"\n + (\" ...\" if len(errors) > 5 else \"\")\n )\n\n if not shapes:\n logger.warning(\n f\"No valid shapes found in mxlibrary '{file_path_or_url}'. \"\n f\"Errors: {'; '.join(errors)}\"\n )\n return {}\n\n return shapes\n\n except (ValueError, FileNotFoundError) as e:\n # Re-raise our custom errors\n raise\n except Exception as e:\n # Catch any unexpected errors\n raise ValueError(\n f\"Unexpected error loading mxlibrary from '{file_path_or_url}': {str(e)}\"\n ) from e", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 2877}, "tests/diagram_tests/legend_test.py::195": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_move_updates_positions", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/xml_base_test.py::123": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_translate_txt_basic", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/legend_test.py::73": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Group", "Legend"], "enclosing_function": "test_default_values", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"\n\n\n# Source: src/drawpyo/diagram/objects.py\nclass Group:\n \"\"\"This class allows objects to be grouped together. It then provides a number of geometry functions and properties to move the entire group around.\n\n Currently this object doesn't replicate any of the functionality of groups in the Draw.io app but it may be extended to have that capability in the future.\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n self.objects: List[Object] = kwargs.get(\"objects\", [])\n self.geometry: Geometry = Geometry()\n\n def add_object(self, object: Union[Object, List[Object]]) -> None:\n \"\"\"Adds one or more objects to the group and updates the geometry of the group.\n\n Args:\n object (Object or list): Object or list of objects to be added to the group\n \"\"\"\n if not isinstance(object, list):\n object = [object]\n for o in object:\n if o not in self.objects:\n self.objects.append(o)\n self.update_geometry()\n\n def update_geometry(self) -> None:\n \"\"\"Update the geometry of the group. This includes the left and top coordinates and the width and height of the entire group.\"\"\"\n self.geometry.x = self.left\n self.geometry.y = self.top\n self.geometry.width = self.width\n self.geometry.height = self.height\n\n ###########################################################\n # Passive properties\n ###########################################################\n\n @property\n def left(self) -> Union[int, float]:\n \"\"\"The leftmost X-coordinate of the objects in the group\n\n Returns:\n int: Left edge of the group\n \"\"\"\n return min([obj.geometry.x for obj in self.objects])\n\n @property\n def right(self) -> Union[int, float]:\n \"\"\"The rightmost X-coordinate of the objects in the group\n\n Returns:\n int: Right edge of the group\n \"\"\"\n return max([obj.geometry.x + obj.geometry.width for obj in self.objects])\n\n @property\n def top(self) -> Union[int, float]:\n \"\"\"The topmost Y-coordinate of the objects in the group\n\n Returns:\n int: Top edge of the group\n \"\"\"\n return min([obj.geometry.y for obj in self.objects])\n\n @property\n def bottom(self) -> Union[int, float]:\n \"\"\"The bottommost Y-coordinate of the objects in the group\n\n Returns:\n int: The bottom edge of the group\n \"\"\"\n return max([obj.geometry.y + obj.geometry.height for obj in self.objects])\n\n @property\n def width(self) -> Union[int, float]:\n \"\"\"The width of all the objects in the group\n\n Returns:\n int: Width of the group\n \"\"\"\n return self.right - self.left\n\n @property\n def height(self) -> Union[int, float]:\n \"\"\"The height of all the objects in the group\n\n Returns:\n int: Height of the group\n \"\"\"\n return self.bottom - self.top\n\n @property\n def size(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The size of the group. Returns a tuple of ints, with the width and height.\n\n Returns:\n tuple: A tuple of ints (width, height)\n \"\"\"\n return (self.width, self.height)\n\n ###########################################################\n # Position properties\n ###########################################################\n\n def _move_by_delta(\n self, delta_x: Union[int, float], delta_y: Union[int, float]\n ) -> None:\n \"\"\"Apply position delta to all objects in the group.\n\n Args:\n delta_x: Horizontal offset to apply\n delta_y: Vertical offset to apply\n \"\"\"\n for obj in self.objects:\n obj.position = (obj.geometry.x + delta_x, obj.geometry.y + delta_y)\n self.update_geometry()\n\n @property\n def center_position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The center position of the group. Returns a tuple of ints, with the X and Y coordinate. When this property is set, the coordinates of every object in the group are updated.\n\n Returns:\n tuple: A tuple of ints (X, Y)\n \"\"\"\n return (self.left + self.width / 2, self.top + self.height / 2)\n\n @center_position.setter\n def center_position(\n self, new_center: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n delta_x = new_center[0] - self.center_position[0]\n delta_y = new_center[1] - self.center_position[1]\n self._move_by_delta(delta_x, delta_y)\n\n @property\n def position(self) -> Tuple[Union[int, float], Union[int, float]]:\n \"\"\"The top left position of the group. Returns a tuple of ints, with the X and Y coordinate. When this property is set, the coordinates of every object in the group are updated.\n\n Returns:\n tuple: A tuple of ints (X, Y)\n \"\"\"\n return (self.left, self.top)\n\n @position.setter\n def position(\n self, new_position: Tuple[Union[int, float], Union[int, float]]\n ) -> None:\n delta_x = new_position[0] - self.position[0]\n delta_y = new_position[1] - self.position[1]\n self._move_by_delta(delta_x, delta_y)", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 12019}, "tests/file_test.py::84": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_remove_page_by_object", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/file_test.py::67": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_multiple_pages", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/color_management_test.py::60": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme", "StandardColor"], "enclosing_function": "test_enum_resolves_to_hex_value", "extracted_code": "# Source: src/drawpyo/utils/standard_colors.py\nclass StandardColor(str, Enum):\n NONE = \"none\"\n BLACK = \"#000000\"\n WHITE = \"#FFFFFF\"\n GRAY1 = \"#E6E6E6\"\n GRAY2 = \"#CCCCCC\"\n GRAY3 = \"#B3B3B3\"\n GRAY4 = \"#999999\"\n GRAY5 = \"#808080\"\n GRAY6 = \"#666666\"\n GRAY7 = \"#4D4D4D\"\n GRAY8 = \"#333333\"\n GRAY9 = \"#1A1A1A\"\n RED1 = \"#FFCCCC\"\n RED2 = \"#FF9999\"\n RED3 = \"#FF6666\"\n RED4 = \"#FF3333\"\n RED5 = \"#FF0000\"\n RED6 = \"#CC0000\"\n RED7 = \"#990000\"\n RED8 = \"#660000\"\n RED9 = \"#330000\"\n ORANGE1 = \"#FFE6CC\"\n ORANGE2 = \"#FFCC99\"\n ORANGE3 = \"#FFB366\"\n ORANGE4 = \"#FF9933\"\n ORANGE5 = \"#FF8000\"\n ORANGE6 = \"#CC6600\"\n ORANGE7 = \"#994C00\"\n ORANGE8 = \"#663300\"\n ORANGE9 = \"#331A00\"\n YELLOW1 = \"#FFFFCC\"\n YELLOW2 = \"#FFFF99\"\n YELLOW3 = \"#FFFF66\"\n YELLOW4 = \"#FFFF33\"\n YELLOW5 = \"#FFFF00\"\n YELLOW6 = \"#CCCC00\"\n YELLOW7 = \"#999900\"\n YELLOW8 = \"#666600\"\n YELLOW9 = \"#333300\"\n LIME1 = \"#E6FFCC\"\n LIME2 = \"#CCFF99\"\n LIME3 = \"#B3FF66\"\n LIME4 = \"#99FF33\"\n LIME5 = \"#80FF00\"\n LIME6 = \"#66CC00\"\n LIME7 = \"#4D9900\"\n LIME8 = \"#336600\"\n LIME9 = \"#1A3300\"\n GREEN1 = \"#CCFFCC\"\n GREEN2 = \"#99FF99\"\n GREEN3 = \"#66FF66\"\n GREEN4 = \"#33FF33\"\n GREEN5 = \"#00FF00\"\n GREEN6 = \"#00CC00\"\n GREEN7 = \"#009900\"\n GREEN8 = \"#006600\"\n GREEN9 = \"#003300\"\n EMERALD1 = \"#CCFFE6\"\n EMERALD2 = \"#99FFCC\"\n EMERALD3 = \"#66FFB3\"\n EMERALD4 = \"#33FF99\"\n EMERALD5 = \"#00FF80\"\n EMERALD6 = \"#00CC66\"\n EMERALD7 = \"#00994D\"\n EMERALD8 = \"#006633\"\n EMERALD9 = \"#00331A\"\n CYAN1 = \"#CCFFFF\"\n CYAN2 = \"#99FFFF\"\n CYAN3 = \"#66FFFF\"\n CYAN4 = \"#33FFFF\"\n CYAN5 = \"#00FFFF\"\n CYAN6 = \"#00CCCC\"\n CYAN7 = \"#009999\"\n CYAN8 = \"#006666\"\n CYAN9 = \"#003333\"\n BLUE1 = \"#CCE5FF\"\n BLUE2 = \"#99CCFF\"\n BLUE3 = \"#66B2FF\"\n BLUE4 = \"#3399FF\"\n BLUE5 = \"#007FFF\"\n BLUE6 = \"#0066CC\"\n BLUE7 = \"#004C99\"\n BLUE8 = \"#003366\"\n BLUE9 = \"#001933\"\n INDIGO1 = \"#CCCCFF\"\n INDIGO2 = \"#9999FF\"\n INDIGO3 = \"#6666FF\"\n INDIGO4 = \"#3333FF\"\n INDIGO5 = \"#0000FF\"\n INDIGO6 = \"#0000CC\"\n INDIGO7 = \"#000099\"\n INDIGO8 = \"#000066\"\n INDIGO9 = \"#000033\"\n PURPLE1 = \"#E5CCFF\"\n PURPLE2 = \"#CC99FF\"\n PURPLE3 = \"#B266FF\"\n PURPLE4 = \"#9933FF\"\n PURPLE5 = \"#7F00FF\"\n PURPLE6 = \"#6600CC\"\n PURPLE7 = \"#6600CC\"\n PURPLE8 = \"#330066\"\n PURPLE9 = \"#190033\"\n MAGENTA1 = \"#FFCCFF\"\n MAGENTA2 = \"#FF99CC\"\n MAGENTA3 = \"#FF66CC\"\n MAGENTA4 = \"#FF33FF\"\n MAGENTA5 = \"#FF00FF\"\n MAGENTA6 = \"#CC00CC\"\n MAGENTA7 = \"#990099\"\n MAGENTA8 = \"#660066\"\n MAGENTA9 = \"#330033\"\n CRIMSON1 = \"#FFCCE6\"\n CRIMSON2 = \"#FF99CC\"\n CRIMSON3 = \"#FF66B3\"\n CRIMSON4 = \"#FF3399\"\n CRIMSON5 = \"#FF0080\"\n CRIMSON6 = \"#CC0066\"\n CRIMSON7 = \"#99004D\"\n CRIMSON8 = \"#660033\"\n CRIMSON9 = \"#33001A\"\n\n\n# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 5549}, "tests/diagram_tests/legend_test.py::101": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_title_object_created", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/object_test.py::92": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_style_string_overwrites_existing", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/bar_chart_test.py::84": {"resolved_imports": ["src/drawpyo/diagram_types/bar_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py"], "used_names": ["BarChart"], "enclosing_function": "test_all_zero_values", "extracted_code": "# Source: src/drawpyo/diagram_types/bar_chart.py\nclass BarChart:\n \"\"\"A configurable bar chart built entirely from Object and Group.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_BAR_WIDTH = 40\n DEFAULT_BAR_SPACING = 20\n DEFAULT_MAX_BAR_HEIGHT = 200\n\n # Spacing constants\n TITLE_BOTTOM_MARGIN = 10\n LABEL_TOP_MARGIN = 5\n BACKGROUND_PADDING = 20\n\n # Axis constants\n AXIS_OFFSET = 10\n TICK_COUNT = 5\n TICK_LENGTH = 4\n TICK_LABEL_MARGIN = 4\n TICK_COLOR = \"#000000\"\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Chart top-left position. Default: (0, 0)\n bar_width (int): Width of each bar. Default: 40\n bar_spacing (int): Space between bars. Default: 20\n max_bar_height (int): Height of the largest bar. Default: 200\n bar_colors (list[Union[str, StandardColor, ColorScheme]]): List of colors. Default: [\"#66ccff\"]\n base_label_formatter (Callable[[str, float], str]): Custom label formatter for base (below) labels. Default: lambda l,v: l\n inside_label_formatter (Callable[[str, float], str]): Custom label formatter for inside-bar labels. Default: lambda l,v: str(v)\n title (str): Optional chart title. Default: None\n title_text_format (TextFormat): TextFormat for the title. Default: TextFormat()\n base_text_format (TextFormat): TextFormat for base labels. Default: TextFormat()\n inside_text_format (TextFormat): TextFormat for inside labels. Default: TextFormat()\n background_color (str | StandardColor): Optional chart background fill. Default: None\n show_axis (bool): Whether to show the axis and ticks. Default: False\n axis_tick_count (int): Number of tick intervals on the axis. Default: 5\n axis_text_format (TextFormat): TextFormat for axis tick labels. Default: TextFormat()\n glass (bool): Whether bars have a glass effect. Default: False\n rounded (bool): Whether bars have rounded corners. Default: False\n \"\"\"\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data: dict[str, Union[int, float]] = data.copy()\n\n # Position and dimensions\n self._position: Optional[tuple[int, int]] = kwargs.get(\"position\", (0, 0))\n self._bar_width: Optional[int] = kwargs.get(\"bar_width\", self.DEFAULT_BAR_WIDTH)\n self._bar_spacing: Optional[int] = kwargs.get(\n \"bar_spacing\", self.DEFAULT_BAR_SPACING\n )\n self._max_bar_height: Optional[int] = kwargs.get(\n \"max_bar_height\", self.DEFAULT_MAX_BAR_HEIGHT\n )\n\n # Text formats\n self._title_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._base_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"base_text_format\", TextFormat())\n )\n self._inside_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"inside_text_format\", TextFormat())\n )\n self._axis_text_format: Optional[TextFormat] = deepcopy(\n kwargs.get(\"axis_text_format\", TextFormat())\n )\n\n # Label formatters\n self._base_label_formatter: Optional[Callable[[str, float], str]] = kwargs.get(\n \"base_label_formatter\", lambda label, value: label\n )\n self._inside_label_formatter: Optional[Callable[[str, float], str]] = (\n kwargs.get(\"inside_label_formatter\", lambda label, value: str(value))\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background color\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n # Axis settings\n self._show_axis: Optional[bool] = kwargs.get(\"show_axis\", False)\n self._axis_tick_count: Optional[int] = kwargs.get(\n \"axis_tick_count\", self.TICK_COUNT\n )\n\n # Bar appearance\n bar_colors: Optional[list[Union[str, StandardColor, ColorScheme]]] = kwargs.get(\n \"bar_colors\", [\"#66ccff\"]\n )\n self._bar_colors: list[Union[str, StandardColor, ColorScheme]] = (\n self._normalize_colors(bar_colors, len(data))\n )\n self._original_bar_colors: Optional[\n list[Union[str, StandardColor, ColorScheme]]\n ] = bar_colors\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Build the chart\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, Union[float, int]]) -> None:\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [key for key in data if not isinstance(key, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings. Invalid: {invalid_keys}\")\n\n invalid_values = [\n key for key, value in data.items() if not isinstance(value, (int, float))\n ]\n if invalid_values:\n raise TypeError(f\"Values must be numeric. Invalid: {invalid_values}\")\n\n self._data = data.copy()\n self._bar_colors = self._normalize_colors(self._original_bar_colors, len(data))\n self._rebuild()\n\n def update_colors(\n self, bar_colors: list[Union[str, StandardColor, ColorScheme]]\n ) -> None:\n self._original_bar_colors = bar_colors\n self._bar_colors = self._normalize_colors(bar_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]) -> None:\n if not isinstance(new_position, (tuple, list)) or len(new_position) != 2:\n raise ValueError(\"new_position must be a tuple of (x, y)\")\n\n dx = new_position[0] - self._position[0]\n dy = new_position[1] - self._position[1]\n\n for obj in self._group.objects:\n old_x, old_y = obj.position\n obj.position = (old_x + dx, old_y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page) -> None:\n for obj in self._group.objects:\n page.add_object(obj)\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(\n self,\n colors: list[Union[str, StandardColor, ColorScheme]],\n count: int,\n ) -> list[Union[str, StandardColor, ColorScheme]]:\n if not colors:\n return [\"#66ccff\"] * count\n\n # Cycle through the list until we have the right amount of colors\n result = []\n for i in range(count):\n result.append(colors[i % len(colors)])\n return result\n\n def _calculate_scale(self) -> float:\n values = list(self._data.values())\n max_value = max(values)\n min_value = min(values)\n\n if min_value < 0:\n raise ValueError(\"Negative values are not currently supported\")\n if max_value == 0:\n return 1\n return self._max_bar_height / max_value\n\n def _calculate_chart_dimensions(self) -> tuple[int, int]:\n num_bars = len(self._data)\n width = num_bars * self._bar_width + (num_bars - 1) * self._bar_spacing\n height = self._max_bar_height\n\n # add space for base labels\n height += (self._base_text_format.fontSize or 12) + self.LABEL_TOP_MARGIN\n\n # add space for title\n if self._title:\n height += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n return width, height\n\n def _rebuild(self) -> None:\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self) -> None:\n x, y = self._position\n scale = self._calculate_scale()\n\n content_y = y\n if self._title:\n content_y += (\n self._title_text_format.fontSize or 16\n ) + self.TITLE_BOTTOM_MARGIN\n\n if self._background_color:\n self._add_background()\n if self._title:\n self._add_title()\n\n # Add ticks and axis if enabled\n if self._show_axis:\n self._add_axis_and_ticks(content_y, scale)\n\n for i, (key, value) in enumerate(self._data.items()):\n self._add_bar_and_label(i, key, value, content_y, scale)\n\n self._group.update_geometry()\n\n def _add_background(self) -> None:\n width, height = self._calculate_chart_dimensions()\n x, y = self._position\n\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=width + 2 * self.BACKGROUND_PADDING,\n height=height + 2 * self.BACKGROUND_PADDING,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self) -> None:\n x, y = self._position\n chart_width, _ = self._calculate_chart_dimensions()\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=chart_width,\n height=(self._title_text_format.fontSize or 16) + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = title_obj.text_format.align or \"center\"\n title_obj.text_format.verticalAlign = (\n title_obj.text_format.verticalAlign or \"top\"\n )\n self._group.add_object(title_obj)\n\n # Draw axis and tick marks\n def _add_axis_and_ticks(self, content_y: int, scale: float) -> None:\n x, _ = self._position\n\n axis_x = x - self._bar_spacing\n axis_y_top = content_y\n axis_y_bottom = content_y + self._max_bar_height\n\n axis_line = Object(\n value=\"\",\n position=(axis_x, axis_y_top),\n width=1,\n height=self._max_bar_height,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(axis_line)\n\n self._add_ticks(axis_x, content_y, scale)\n\n def _add_ticks(self, axis_x: int, content_y: int, scale: float) -> None:\n if self._axis_tick_count < 1:\n return\n\n max_value = max(self._data.values())\n font_size = self._axis_text_format.fontSize or 12\n\n for i in range(self._axis_tick_count + 1):\n t = i / self._axis_tick_count\n\n tick_value = max_value * (1 - t)\n tick_y = content_y + (self._max_bar_height * t)\n\n tick = Object(\n value=\"\",\n position=(axis_x - self.TICK_LENGTH, tick_y),\n width=self.TICK_LENGTH,\n height=1,\n fillColor=None,\n strokeColor=self.TICK_COLOR,\n )\n self._group.add_object(tick)\n\n label_obj = Object(\n value=str(round(tick_value, 2)),\n position=(\n axis_x - self.TICK_LENGTH - self.TICK_LABEL_MARGIN - 40,\n tick_y - font_size / 2,\n ),\n width=40,\n height=font_size + 4,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._axis_text_format)\n label_obj.text_format.align = \"right\"\n self._group.add_object(label_obj)\n\n def _add_bar_and_label(\n self, index: int, key: str, value: float, content_y: int, scale: float\n ) -> None:\n x, _ = self._position\n bar_height = value * scale\n if isinstance(self._bar_colors[index], ColorScheme):\n color_scheme = self._bar_colors[index]\n elif isinstance(self._bar_colors[index], (StandardColor, str)):\n fill_color = self._bar_colors[index]\n\n # Calculate geometry\n bar_x = x + index * (self._bar_width + self._bar_spacing)\n bar_y = content_y + (self._max_bar_height - bar_height)\n bar_width = self._bar_width\n\n # Resolve color\n color_value = self._bar_colors[index]\n color_scheme = color_value if isinstance(color_value, ColorScheme) else None\n fill_color = None if color_scheme else color_value\n\n # INSIDE LABEL\n inside_label = self._inside_label_formatter(key, value)\n inside_text_format = deepcopy(self._inside_text_format)\n inside_text_format.align = inside_text_format.align or \"center\"\n inside_text_format.verticalAlign = inside_text_format.verticalAlign or \"middle\"\n\n bar = Object(\n value=inside_label,\n position=(bar_x, bar_y),\n width=bar_width,\n height=bar_height,\n color_scheme=color_scheme,\n fillColor=fill_color,\n rounded=self._rounded,\n glass=self._glass,\n text_format=inside_text_format,\n )\n\n self._group.add_object(bar)\n\n # BASE LABEL\n base_label = self._base_label_formatter(key, value)\n base_obj = Object(\n value=base_label,\n position=(bar_x, content_y + self._max_bar_height + self.LABEL_TOP_MARGIN),\n width=bar_width,\n height=(self._base_text_format.fontSize or 12) + 10,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n base_obj.text_format = deepcopy(self._base_text_format)\n base_obj.text_format.align = base_obj.text_format.align or \"center\"\n self._group.add_object(base_obj)\n\n def __repr__(self) -> str:\n return f\"BarChart(bars={len(self._data)}, position={self._position})\"\n\n def __len__(self) -> int:\n return len(self._data)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 15374}, "tests/import_tests/test_mxlibrary_import.py::77": {"resolved_imports": ["src/drawpyo/drawio_import/mxlibrary_parser.py", "src/drawpyo/__init__.py"], "used_names": ["load_mxlibrary"], "enclosing_function": "test_load_mxlibrary_from_local_file", "extracted_code": "# Source: src/drawpyo/drawio_import/mxlibrary_parser.py\ndef load_mxlibrary(file_path_or_url: str) -> Dict[str, Dict[str, Any]]:\n \"\"\"\n Loads an mxlibrary from a file path or URL and parses it.\n\n Args:\n file_path_or_url: Local file path or HTTP/HTTPS URL.\n\n Returns:\n Dictionary of shapes.\n\n Raises:\n ValueError: If the file/URL cannot be loaded or parsed.\n FileNotFoundError: If the local file doesn't exist.\n urllib.error.URLError: If the URL cannot be accessed.\n \"\"\"\n content = \"\"\n\n try:\n if file_path_or_url.lower().startswith((\"http://\", \"https://\")):\n try:\n with urllib.request.urlopen(file_path_or_url, timeout=30) as response:\n content = response.read().decode(\"utf-8\")\n except urllib.error.HTTPError as e:\n raise ValueError(\n f\"Failed to fetch mxlibrary from URL '{file_path_or_url}': \"\n f\"HTTP {e.code} - {e.reason}\"\n ) from e\n except urllib.error.URLError as e:\n raise ValueError(\n f\"Failed to access URL '{file_path_or_url}': {str(e.reason)}\"\n ) from e\n except Exception as e:\n raise ValueError(\n f\"Unexpected error fetching URL '{file_path_or_url}': {str(e)}\"\n ) from e\n else:\n try:\n with open(file_path_or_url, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n except FileNotFoundError:\n raise FileNotFoundError(\n f\"mxlibrary file not found: '{file_path_or_url}'\"\n )\n except PermissionError:\n raise ValueError(\n f\"Permission denied reading file: '{file_path_or_url}'\"\n )\n except Exception as e:\n raise ValueError(\n f\"Error reading file '{file_path_or_url}': {str(e)}\"\n ) from e\n\n shapes, errors = parse_mxlibrary(content)\n\n if errors:\n logger.warning(\n f\"Encountered {len(errors)} error(s) while parsing mxlibrary \"\n f\"from '{file_path_or_url}': {'; '.join(errors[:5])}\"\n + (\" ...\" if len(errors) > 5 else \"\")\n )\n\n if not shapes:\n logger.warning(\n f\"No valid shapes found in mxlibrary '{file_path_or_url}'. \"\n f\"Errors: {'; '.join(errors)}\"\n )\n return {}\n\n return shapes\n\n except (ValueError, FileNotFoundError) as e:\n # Re-raise our custom errors\n raise\n except Exception as e:\n # Catch any unexpected errors\n raise ValueError(\n f\"Unexpected error loading mxlibrary from '{file_path_or_url}': {str(e)}\"\n ) from e", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 2877}, "tests/file_test.py::69": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_add_multiple_pages", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/edge_test.py::438": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Point"], "enclosing_function": "test_point_default_values", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Point(DiagramBase):\n def __init__(self, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.xml_class: str = \"mxPoint\"\n\n self.x: int = kwargs.get(\"x\", 0)\n self.y: int = kwargs.get(\"y\", 0)\n\n @property\n def attributes(self) -> Dict[str, int]:\n return {\"x\": self.x, \"y\": self.y}", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 370}, "tests/diagram_tests/binary_tree_diagram_test.py::43": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject"], "enclosing_function": "test_set_same_child_idempotent", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4036}, "tests/xml_base_test.py::114": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_xml_ify_preserves_normal_text", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/xml_base_test.py::59": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_attributes_with_parent", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/color_management_test.py::207": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": [], "enclosing_function": "test_hierarchy_defaults_used_when_both_missing", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/diagram_tests/base_diagram_test.py::81": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["width_input_check"], "enclosing_function": "test_valid_width", "extracted_code": "# Source: src/drawpyo/diagram/base_diagram.py\ndef width_input_check(width: Optional[Union[int, str]]) -> Optional[int]:\n if not width or (isinstance(width, str) and not width.isdigit()):\n return None\n\n width = int(width)\n if width < 1:\n return 1\n elif width > 999:\n return 999\n else:\n return width", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 340}, "tests/diagram_tests/color_management_test.py::222": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme"], "enclosing_function": "test_hierarchy_scheme_used_if_no_object_specific_font", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/xml_base_test.py::41": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_with_tag", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/binary_tree_diagram_test.py::99": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject", "BinaryTreeDiagram"], "enclosing_function": "test_add_left_and_add_right_assign_tree", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)\n\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 12864}, "tests/diagram_tests/color_management_test.py::133": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme"], "enclosing_function": "test_none_values_allowed", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/binary_tree_diagram_test.py::56": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryNodeObject"], "enclosing_function": "test_move_child_between_parents_using_properties", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryNodeObject(NodeObject):\n \"\"\"\n NodeObject variant for binary trees exposing `left` and `right` properties\n and enforcing at most two children.\n \"\"\"\n\n def __init__(self, tree=None, **kwargs) -> None:\n \"\"\"\n Initialize a binary node with exactly 2 child slots [left, right].\n\n If `tree_children` is provided, it is normalized to two elements.\n \"\"\"\n children: List[Optional[BinaryNodeObject]] = kwargs.get(\"tree_children\", [])\n\n # Normalize provided list to exactly 2 elements\n if len(children) == 0:\n normalized = [None, None]\n elif len(children) == 1:\n normalized = [children[0], None]\n elif len(children) == 2:\n normalized = children[:]\n else:\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n kwargs[\"tree_children\"] = normalized\n super().__init__(tree=tree, **kwargs)\n\n # ---------------------------------------------------------\n # Private methods\n # ---------------------------------------------------------\n\n def _ensure_two_slots(self) -> None:\n \"\"\"Ensure tree_children always has exactly 2 slots.\"\"\"\n if len(self.tree_children) < 2:\n missing = 2 - len(self.tree_children)\n self.tree_children.extend([None] * missing)\n elif len(self.tree_children) > 2:\n self.tree_children[:] = self.tree_children[:2]\n\n def _detach_from_old_parent(self, node: NodeObject) -> None:\n \"\"\"Remove `node` from its old parent's children (if any).\"\"\"\n parent = getattr(node, \"tree_parent\", None)\n if parent is None or parent is self:\n return\n\n if hasattr(parent, \"tree_children\"):\n for i, existing in enumerate(parent.tree_children):\n if existing is node:\n parent.tree_children[i] = None\n break\n\n node._tree_parent = None\n\n def _clear_existing_slot(self, node: NodeObject, target_index: int) -> None:\n \"\"\"\n If `node` already belongs to this parent in the *other* slot,\n clear the old slot.\n \"\"\"\n for i, existing in enumerate(self.tree_children):\n if existing is node and i != target_index:\n self.tree_children[i] = None\n\n def _assign_child(self, index: int, node: Optional[NodeObject]) -> None:\n \"\"\"\n Handles:\n - Ensuring slot count\n - Clearing old child if assigning None\n - Preventing more than 2 distinct children\n - Correctly detaching and reattaching node\n \"\"\"\n self._ensure_two_slots()\n existing = self.tree_children[index]\n\n if node is None:\n if existing is not None:\n self.tree_children[index] = None\n existing._tree_parent = None\n return\n\n if not node in self.tree_children:\n other = 1 - index\n if (\n self.tree_children[index] is not None\n and self.tree_children[other] is not None\n ):\n raise ValueError(\"BinaryNodeObject cannot have more than two children\")\n\n self._detach_from_old_parent(node)\n\n self._clear_existing_slot(node, index)\n\n self.tree_children[index] = node\n node._tree_parent = self\n\n # ---------------------------------------------------------\n # Properties and setters\n # ---------------------------------------------------------\n\n @property\n def left(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[0]\n\n @left.setter\n def left(self, node: Optional[NodeObject]) -> None:\n self._assign_child(0, node)\n\n @property\n def right(self) -> Optional[NodeObject]:\n self._ensure_two_slots()\n return self.tree_children[1]\n\n @right.setter\n def right(self, node: Optional[NodeObject]) -> None:\n self._assign_child(1, node)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4036}, "tests/diagram_tests/legend_test.py::198": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_move_updates_positions", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/pie_chart_test.py::423": {"resolved_imports": ["src/drawpyo/diagram_types/pie_chart.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/diagram/objects.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["PieChart"], "enclosing_function": "test_many_slices", "extracted_code": "# Source: src/drawpyo/diagram_types/pie_chart.py\nclass PieChart:\n \"\"\"A configurable pie chart built entirely from Object, Group, and PieSlice.\n\n This chart is mutable - you can update data, styling, and position after creation.\n \"\"\"\n\n # Layout constants\n DEFAULT_SIZE = 200\n TITLE_BOTTOM_MARGIN = 20\n LABEL_OFFSET = 5\n BACKGROUND_PADDING = 20\n\n def __init__(self, data: dict[str, float], **kwargs):\n \"\"\"\n Args:\n data (dict[str, float]): Mapping of labels to numeric values.\n\n Keyword Args:\n position (tuple[int, int]): Top-left chart position. Default: (0, 0)\n size (int): Diameter of the pie. Default: 200\n slice_colors (list[str | StandardColor | ColorScheme]): Colors for slices.\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n background_color (str | StandardColor): Optional chart background.\n label_formatter (Callable[[str, float], str]): Custom formatter for slice labels.\n \"\"\"\n\n # Validate data\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n invalid_keys = [k for k in data if not isinstance(k, str)]\n if invalid_keys:\n raise TypeError(f\"All keys must be strings: {invalid_keys}\")\n\n invalid_values = [k for k, v in data.items() if not isinstance(v, (int, float))]\n if invalid_values:\n raise TypeError(f\"Values must be numeric: {invalid_values}\")\n\n self._data: dict[str, float] = data.copy()\n\n # Position and size\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n self._size: int = kwargs.get(\"size\", self.DEFAULT_SIZE)\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Background\n self._background_color = kwargs.get(\"background_color\")\n\n # Colors\n slice_colors: list[Union[str, StandardColor, ColorScheme]] = kwargs.get(\n \"slice_colors\", [\"#66ccff\"]\n )\n self._slice_colors: list = self._normalize_colors(slice_colors, len(data))\n self._original_slice_colors = slice_colors\n\n # Label formatting\n self._label_formatter: Callable[[str, float, float], str] = kwargs.get(\n \"label_formatter\", self.default_label_formatter\n )\n\n # Build\n self._group: Group = Group()\n self._build_chart()\n\n # ------------------------------------------------------------------\n # Properties\n # ------------------------------------------------------------------\n\n @property\n def data(self) -> dict[str, float]:\n return self._data.copy()\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n @property\n def group(self) -> Group:\n return self._group\n\n # ------------------------------------------------------------------\n # Public methods\n # ------------------------------------------------------------------\n\n def update_data(self, data: dict[str, float]) -> None:\n if not isinstance(data, dict):\n raise TypeError(\"Data must be a dict.\")\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n self._data = data.copy()\n self._slice_colors = self._normalize_colors(\n self._original_slice_colors, len(data)\n )\n self._rebuild()\n\n def update_colors(self, slice_colors: list[Union[str, StandardColor, ColorScheme]]):\n self._original_slice_colors = slice_colors\n self._slice_colors = self._normalize_colors(slice_colors, len(self._data))\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n ox, oy = obj.position\n obj.position = (ox + dx, oy + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n def default_label_formatter(self, key, value, total):\n return f\"{key}: {value/total*100:.1f}%\"\n\n # ------------------------------------------------------------------\n # Private methods\n # ------------------------------------------------------------------\n\n def _normalize_colors(self, colors, count):\n if not colors:\n return [\"#66ccff\"] * count\n return [colors[i % len(colors)] for i in range(count)]\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build_chart()\n\n def _build_chart(self):\n x, y = self._position\n\n # Compute vertical offsets if title is present\n title_h = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n pie_y = y + title_h\n\n if self._background_color:\n self._add_background(title_h)\n if self._title:\n self._add_title()\n\n total = sum(self._data.values())\n if total == 0:\n total = 1.0 # Avoid division by zero\n\n start_angle = 0.0\n\n for i, (label, value) in enumerate(self._data.items()):\n fraction = value / total if total else 0\n slice_color = self._slice_colors[i]\n\n slice_obj = PieSlice(\n value=\"\",\n slice_value=fraction,\n position=(x, pie_y),\n size=self._size,\n startAngle=start_angle,\n fillColor=None if isinstance(slice_color, ColorScheme) else slice_color,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n )\n\n self._group.add_object(slice_obj)\n\n # SLICE LABEL\n slice_label_pos = self._get_slice_label_position(\n start_angle, fraction, x, pie_y\n )\n slice_text = self._label_formatter(label, value, total)\n slice_label = Object(\n value=slice_text,\n position=slice_label_pos,\n width=self._size,\n height=self._size,\n color_scheme=(\n slice_color if isinstance(slice_color, ColorScheme) else None\n ),\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n self._group.add_object(slice_label)\n\n start_angle += fraction\n\n self._group.update_geometry()\n\n def _get_slice_label_position(\n self, start_angle: float, fraction: float, x: int, y: int\n ) -> tuple[int, int]:\n import math\n\n # Mittelpunktwinkel der Scheibe (normalisiert 0–1)\n mid_angle = start_angle + (fraction / 2)\n\n # In Radiant umrechnen (Uhrzeigersinn)\n theta = (mid_angle * 2 * math.pi) - (math.pi / 2)\n\n # Radius + Offset\n offset = (self._size / 4) + self.LABEL_OFFSET\n\n # Kreisposition berechnen\n label_x = x + math.cos(theta) * offset\n label_y = y + math.sin(theta) * offset\n\n return (label_x, label_y)\n\n def _add_background(self, title_h: int):\n x, y = self._position\n size = self._size\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=size + 2 * self.BACKGROUND_PADDING,\n height=size + 2 * self.BACKGROUND_PADDING + title_h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n title_height = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=self._size,\n height=title_height,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"center\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def __repr__(self):\n return f\"PieChart(slices={len(self._data)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8838}, "tests/diagram_tests/object_test.py::138": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/utils/standard_colors.py"], "used_names": ["drawpyo"], "enclosing_function": "test_template_chain", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/diagram_tests/binary_tree_diagram_test.py::250": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram_types/binary_tree.py"], "used_names": ["BinaryTreeDiagram"], "enclosing_function": "test_from_dict_nested_structure", "extracted_code": "# Source: src/drawpyo/diagram_types/binary_tree.py\nclass BinaryTreeDiagram(TreeDiagram):\n \"\"\"Simplifies TreeDiagram for binary-tree convenience.\"\"\"\n\n DEFAULT_LEVEL_SPACING = 80\n DEFAULT_ITEM_SPACING = 20\n DEFAULT_GROUP_SPACING = 30\n DEFAULT_LINK_STYLE = \"straight\"\n\n def __init__(self, **kwargs) -> None:\n kwargs.setdefault(\"level_spacing\", self.DEFAULT_LEVEL_SPACING)\n kwargs.setdefault(\"item_spacing\", self.DEFAULT_ITEM_SPACING)\n kwargs.setdefault(\"group_spacing\", self.DEFAULT_GROUP_SPACING)\n kwargs.setdefault(\"link_style\", self.DEFAULT_LINK_STYLE)\n super().__init__(**kwargs)\n\n def _attach(\n self, parent: BinaryNodeObject, child: BinaryNodeObject, side: str\n ) -> None:\n if not isinstance(parent, BinaryNodeObject) or not isinstance(\n child, BinaryNodeObject\n ):\n raise TypeError(\"parent and child must be BinaryNodeObject instances\")\n\n if parent.tree is not self:\n parent.tree = self\n child.tree = self\n\n setattr(parent, side, child)\n\n def add_left(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"left\")\n\n def add_right(self, parent: BinaryNodeObject, child: BinaryNodeObject) -> None:\n self._attach(parent, child, \"right\")\n\n @classmethod\n def from_dict(\n cls,\n data: dict,\n *,\n colors: list = None,\n coloring: str = \"depth\",\n **kwargs,\n ) -> \"BinaryTreeDiagram\":\n \"\"\"\n Build a BinaryTreeDiagram from nested dict/list structures.\n data: Nested dict/list structure representing the tree.\n colors: List of ColorSchemes, StandardColors, or color hex strings to use for coloring nodes. Default: None\n coloring: str - \"depth\" | \"hash\" | \"type\" | \"directional\" - Method to match colors to nodes. Default: \"depth\"\n 1. \"depth\" - Color nodes based on their depth in the tree.\n 2. \"hash\" - Color nodes based on a hash of their value.\n 3. \"type\" - Color nodes based on their type (category, list_item, leaf).\n 4. \"directional\" - Color nodes based on their direction (left, right).\n\n Note: In colors Left Nodes are coloured by 0th index and Right Nodes are coloured by 1st index in the list of colors.\n \"\"\"\n\n if coloring not in {\"depth\", \"hash\", \"type\", \"directional\"}:\n raise ValueError(f\"Invalid coloring mode: {coloring}\")\n\n if colors is not None and not isinstance(colors, list):\n raise TypeError(\"colors must be a list or None\")\n\n colors = colors or None\n TYPE_INDEX = {\"category\": 0, \"list_item\": 1, \"leaf\": 2}\n\n # -------------------------\n # Validation\n # -------------------------\n\n def validate(tree_node: Dict, *, is_root=False):\n if tree_node is None or isinstance(tree_node, (str, int, float)):\n return\n\n if isinstance(tree_node, (list, tuple)):\n if len(tree_node) > 2:\n raise TypeError(\"List node can have at most two children\")\n for x in tree_node:\n validate(x)\n return\n\n if isinstance(tree_node, dict):\n if is_root and len(tree_node) != 1:\n raise TypeError(\"Root dict must contain exactly one key\")\n\n if not is_root and not (1 <= len(tree_node) <= 2):\n raise TypeError(\"Dict node must have 1 or 2 children\")\n\n for node, children in tree_node.items():\n if not isinstance(node, (str, int, float)):\n raise TypeError(f\"Invalid dict key type: {type(node)}\")\n\n validate(children)\n return\n\n raise TypeError(f\"Unsupported tree tree_node type: {type(tree_node)}\")\n\n if not isinstance(data, dict):\n raise TypeError(\"Top-level tree must be a dict\")\n\n # Checks if the provided dict data is valid for a binary tree construction\n validate(data, is_root=True)\n\n # -------------------------\n # Helpers\n # -------------------------\n\n diagram = cls(**kwargs)\n\n def choose_color(\n value: str, node_type: str, depth: int, side: Optional[object] = None\n ):\n if not colors:\n return None\n\n n = len(colors)\n\n if coloring == \"depth\":\n idx = depth % n\n elif coloring == \"hash\":\n h = int(hashlib.md5(value.encode()).hexdigest(), 16)\n idx = h % n\n elif coloring == \"directional\":\n # side can be 'left'/'right' or a boolean where True==left\n if n < 2:\n raise ValueError(\n \"colors list must be of length at least 2 for directional coloring\"\n )\n\n if side is None:\n return None\n\n if isinstance(side, bool):\n is_left = side\n else:\n is_left = str(side).lower() == \"left\"\n\n idx = (0 if is_left else 1) % n\n\n else: # type\n idx = TYPE_INDEX[node_type] % n\n\n return colors[idx]\n\n def create_node(value: str, parent, color):\n if color is None:\n return BinaryNodeObject(tree=diagram, value=value, tree_parent=parent)\n\n if isinstance(color, drawpyo.ColorScheme):\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, color_scheme=color\n )\n\n return BinaryNodeObject(\n tree=diagram, value=value, tree_parent=parent, fillColor=color\n )\n\n # -------------------------\n # Build\n # -------------------------\n\n def build(parent: BinaryNodeObject, item: Any, depth: int):\n if item is None:\n return\n\n # Leaf\n if isinstance(item, (str, int, float)):\n value = str(item)\n # leaf nodes in this branch are always attached as left\n node = create_node(\n value,\n parent,\n choose_color(value, \"leaf\", depth, side=\"left\"),\n )\n diagram.add_left(parent, node)\n return\n\n # Dict (named children)\n if isinstance(item, dict):\n for index, (node, children) in enumerate(item.items()):\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth, side=side),\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n build(node, children, depth + 1)\n return\n\n # List / Tuple (positional children)\n for index, elem in enumerate(item):\n if elem is None:\n continue\n\n if isinstance(elem, (str, int, float)):\n name = str(elem)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"leaf\", depth + 1, side=side),\n )\n\n elif isinstance(elem, dict) and len(elem) == 1:\n node, children = next(iter(elem.items()))\n name = str(node)\n side = \"left\" if index == 0 else \"right\"\n node = create_node(\n name,\n parent,\n choose_color(name, \"category\", depth + 1, side=side),\n )\n build(node, children, depth + 1)\n else:\n raise TypeError(\n \"List elements must be primitive or single-key dict\"\n )\n\n if index == 0:\n diagram.add_left(parent, node)\n else:\n diagram.add_right(parent, node)\n\n # -------------------------\n # Root\n # -------------------------\n\n root_key, root_value = next(iter(data.items()))\n root_name = str(root_key)\n\n root = create_node(\n root_name,\n None,\n choose_color(root_name, \"category\", 0, None),\n )\n\n build(root, root_value, depth=1)\n diagram.auto_layout()\n return diagram", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8877}, "tests/diagram_tests/edge_test.py::235": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_opacity", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/diagram_tests/color_management_test.py::41": {"resolved_imports": ["src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["ColorScheme", "pytest"], "enclosing_function": "test_is_valid_hex_raises_for_non_string", "extracted_code": "# Source: src/drawpyo/utils/color_scheme.py\nclass ColorScheme:\n \"\"\"\n Represents a set of colors used for an object's fill, stroke and font.\n\n A color can be:\n • None\n • A hex string\n • A DefaultColor\n \"\"\"\n\n HEX_PATTERN = re.compile(r\"^#[0-9A-Fa-f]{6}$\")\n\n ###########################################################\n # Initialization\n ###########################################################\n\n def __init__(\n self,\n fill_color: ColorType = None,\n stroke_color: ColorType = None,\n font_color: ColorType = None,\n ) -> None:\n self.fill_color: ColorType = self._validated(fill_color)\n self.stroke_color: ColorType = self._validated(stroke_color)\n self.font_color: ColorType = self._validated(font_color)\n logger.info(f\"🎨 ColorScheme created: {self.__repr__()}\")\n\n ###########################################################\n # Public Setters\n ###########################################################\n\n def set_fill_color(self, color: ColorType) -> None:\n self.fill_color = self._validated(color)\n\n def set_stroke_color(self, color: ColorType) -> None:\n self.stroke_color = self._validated(color)\n\n def set_font_color(self, color: ColorType) -> None:\n self.font_color = self._validated(color)\n\n ###########################################################\n # Validation\n ###########################################################\n\n def _validated(self, color: ColorType) -> ColorType:\n \"\"\"Validate hex strings or DefaultColor enums.\"\"\"\n if color is None:\n return None\n\n if isinstance(color, StandardColor):\n return color.value\n\n if isinstance(color, str):\n if not self.is_valid_hex(color):\n raise ValueError(\n f\"Invalid color '{color}'. \"\n f\"Expected '#RRGGBB' (example: #A1B2C3).\"\n )\n return color.upper()\n\n raise TypeError(\n f\"Color must be a hex string like '#AABBCC', None, or a DefaultColor enum. \"\n f\"Received: {type(color)}\"\n )\n\n @classmethod\n def is_valid_hex(cls, value: str) -> bool:\n \"\"\"Return True if string is a valid #RRGGBB hex color.\"\"\"\n return bool(cls.HEX_PATTERN.match(value))\n\n ###########################################################\n # Utility\n ###########################################################\n\n def __repr__(self) -> str:\n return (\n f\"fill: {self.fill_color} \"\n f\"| stroke: {self.stroke_color} \"\n f\"| font: {self.font_color}\"\n )", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2679}, "tests/diagram_tests/legend_test.py::196": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend"], "enclosing_function": "test_move_updates_positions", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/diagram_tests/base_diagram_test.py::220": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/base_diagram.py"], "used_names": ["drawpyo"], "enclosing_function": "test_geometry_init_custom", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/diagram_tests/edge_test.py::78": {"resolved_imports": ["src/drawpyo/__init__.py", "src/drawpyo/diagram/edges.py", "src/drawpyo/utils/color_scheme.py"], "used_names": ["Edge", "drawpyo"], "enclosing_function": "test_stroke_width", "extracted_code": "# Source: src/drawpyo/diagram/edges.py\nclass Edge(DiagramBase):\n \"\"\"The Edge class is the simplest class for defining an edge or an arrow in a Draw.io diagram.\n\n The three primary styling inputs are the waypoints, connections, and pattern. These are how edges are styled in the Draw.io app, with dropdown menus for each one. But it's not how the style string is assembled in the XML. To abstract this, the Edge class loads a database called edge_styles.toml. The database maps the options in each dropdown to the style strings they correspond to. The Edge class then assembles the style strings on export.\n\n More information about edges are in the Usage documents at [Usage - Edges](../../usage/edges).\n \"\"\"\n\n def __init__(self, **kwargs: Any) -> None:\n \"\"\"Edges can be initialized with almost all styling parameters as args.\n See [Usage - Edges](../../usage/edges) for more information and the options for each parameter.\n\n Args:\n source (DiagramBase): The Draw.io object that the edge originates from\n target (DiagramBase): The Draw.io object that the edge points to\n label (str): The text to place on the edge.\n label_position (float): Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center\n label_offset (int): How far the label is offset away from the axis of the edge in pixels\n waypoints (str): How the edge should be styled in Draw.io\n connection (str): What type of style the edge should be rendered with\n pattern (str): How the line of the edge should be rendered\n shadow (bool, optional): Add a shadow to the edge\n rounded (bool): Whether the corner of the line should be rounded\n flowAnimation (bool): Add a marching ants animation along the edge\n sketch (bool, optional): Add sketch styling to the edge\n line_end_target (str): What graphic the edge should be rendered with at the target\n line_end_source (str): What graphic the edge should be rendered with at the source\n endFill_target (boolean): Whether the target graphic should be filled\n endFill_source (boolean): Whether the source graphic should be filled\n endSize (int): The size of the end arrow in points\n startSize (int): The size of the start arrow in points\n jettySize (str or int): Length of the straight sections at the end of the edge. \"auto\" or a number\n targetPerimeterSpacing (int): The negative or positive spacing between the target and end of the edge (points)\n sourcePerimeterSpacing (int): The negative or positive spacing between the source and end of the edge (points)\n entryX (int): From where along the X axis on the source object the edge originates (0-1)\n entryY (int): From where along the Y axis on the source object the edge originates (0-1)\n entryDx (int): Applies an offset in pixels to the X axis entry point\n entryDy (int): Applies an offset in pixels to the Y axis entry point\n exitX (int): From where along the X axis on the target object the edge originates (0-1)\n exitY (int): From where along the Y axis on the target object the edge originates (0-1)\n exitDx (int): Applies an offset in pixels to the X axis exit point\n exitDy (int): Applies an offset in pixels to the Y axis exit point\n color_scheme (ColorScheme, optional): Bundled set of color specifications. Defaults to None.\n strokeColor (str): The color of the border of the edge ('none', 'default', or hex color code)\n strokeWidth (int): The width of the border of the the edge within range (1-999)\n fillColor (str): The color of the fill of the edge ('none', 'default', or hex color code)\n jumpStyle (str): The line jump style ('arc', 'gap', 'sharp', 'line')\n jumpSize (int): The size of the line jumps in points.\n opacity (int): The opacity of the edge (0-100)\n \"\"\"\n super().__init__(**kwargs)\n self.xml_class: str = \"mxCell\"\n\n # Style\n self.color_scheme: Optional[ColorScheme] = kwargs.get(\"color_scheme\", None)\n self.text_format: Optional[TextFormat] = kwargs.get(\"text_format\", TextFormat())\n if not self.text_format.fontColor and self.color_scheme:\n self.text_format.fontColor = self.color_scheme.font_color\n self.waypoints: Optional[str] = kwargs.get(\"waypoints\", \"orthogonal\")\n self.connection: Optional[str] = kwargs.get(\"connection\", \"line\")\n self.pattern: Optional[str] = kwargs.get(\"pattern\", \"solid\")\n self.opacity: Optional[int] = kwargs.get(\"opacity\", None)\n self.strokeWidth: Optional[int] = kwargs.get(\"strokeWidth\", None)\n self.strokeColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"stroke_color\"\n ) or (self.color_scheme.stroke_color if self.color_scheme else None)\n self.fillColor: Optional[Union[str, StandardColor]] = kwargs.get(\n \"fill_color\"\n ) or (self.color_scheme.fill_color if self.color_scheme else None)\n\n # Line end\n self.line_end_target: Optional[str] = kwargs.get(\"line_end_target\", None)\n self.line_end_source: Optional[str] = kwargs.get(\"line_end_source\", None)\n self.endFill_target: bool = kwargs.get(\"endFill_target\", False)\n self.endFill_source: bool = kwargs.get(\"endFill_source\", False)\n self.endSize: Optional[int] = kwargs.get(\"endSize\", None)\n self.startSize: Optional[int] = kwargs.get(\"startSize\", None)\n\n self.rounded: int = kwargs.get(\"rounded\", 0)\n self.sketch: Optional[bool] = kwargs.get(\"sketch\", None)\n self.shadow: Optional[bool] = kwargs.get(\"shadow\", None)\n self.flowAnimation: Optional[bool] = kwargs.get(\"flowAnimation\", None)\n\n self._jumpStyle: Optional[str] = None\n self.jumpStyle = kwargs.get(\"jumpStyle\", None)\n self.jumpSize: Optional[int] = kwargs.get(\"jumpSize\", None)\n\n # Connection and geometry\n self.jettySize: Union[str, int] = kwargs.get(\"jettySize\", \"auto\")\n self.geometry: EdgeGeometry = EdgeGeometry()\n self.edge: int = kwargs.get(\"edge\", 1)\n self.targetPerimeterSpacing: Optional[int] = kwargs.get(\n \"targetPerimeterSpacing\", None\n )\n self.sourcePerimeterSpacing: Optional[int] = kwargs.get(\n \"sourcePerimeterSpacing\", None\n )\n self._source: Optional[DiagramBase] = None\n self.source = kwargs.get(\"source\", None)\n self._target: Optional[DiagramBase] = None\n self.target = kwargs.get(\"target\", None)\n self.entryX: Optional[float] = kwargs.get(\"entryX\", None)\n self.entryY: Optional[float] = kwargs.get(\"entryY\", None)\n self.entryDx: Optional[int] = kwargs.get(\"entryDx\", None)\n self.entryDy: Optional[int] = kwargs.get(\"entryDy\", None)\n self.exitX: Optional[float] = kwargs.get(\"exitX\", None)\n self.exitY: Optional[float] = kwargs.get(\"exitY\", None)\n self.exitDx: Optional[int] = kwargs.get(\"exitDx\", None)\n self.exitDy: Optional[int] = kwargs.get(\"exitDy\", None)\n\n # Label\n self.label: Optional[str] = kwargs.get(\"label\", None)\n self.edge_axis_offset: Optional[int] = kwargs.get(\"edge_offset\", None)\n self.label_offset: Optional[int] = kwargs.get(\"label_offset\", None)\n self.label_position: Optional[float] = kwargs.get(\"label_position\", None)\n\n logger.debug(f\"➡️ Edge created: {self.__repr__()}\")\n\n def __repr__(self) -> str:\n \"\"\"\n A concise and informative representation of the edge for debugging.\n \"\"\"\n cls = self.__class__.__name__\n parts = []\n\n # Source/Target\n parts.append(f\"source: '{self.source.value if self.source else None}'\")\n parts.append(f\"target: '{self.target.value if self.target else None}'\")\n\n # Label\n if self.label:\n parts.append(f\"label={self.label!r}\")\n\n # Entry/Exit geometry (only show if anything is set)\n geom_parts = []\n for attr in (\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n ):\n val = getattr(self, attr, None)\n if val not in (None, 0):\n geom_parts.append(f\"{attr}={val}\")\n if geom_parts:\n parts.append(\"geom={\" + \", \".join(geom_parts) + \"}\")\n\n return f\"{cls}(\" + \", \".join(parts) + \")\"\n\n def __str__(self) -> str:\n return self.__repr__()\n\n def remove(self) -> None:\n \"\"\"This function removes references to the Edge from its source and target objects then deletes the Edge.\"\"\"\n if self.source is not None:\n self.source.remove_out_edge(self)\n if self.target is not None:\n self.target.remove_in_edge(self)\n del self\n\n @property\n def attributes(self) -> Dict[str, Any]:\n \"\"\"Returns the XML attributes to be added to the tag for the object\n\n Returns:\n dict: Dictionary of object attributes and their values\n \"\"\"\n base_attr_dict: Dict[str, Any] = {\n \"id\": self.id,\n \"style\": self.style,\n \"edge\": self.edge,\n \"parent\": self.xml_parent_id,\n \"source\": self.source_id,\n \"target\": self.target_id,\n }\n if self.value is not None:\n base_attr_dict[\"value\"] = self.value\n return base_attr_dict\n\n ###########################################################\n # Source and Target Linking\n ###########################################################\n\n # Source\n @property\n def source(self) -> Optional[DiagramBase]:\n \"\"\"The source object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: source object of the edge\n \"\"\"\n return self._source\n\n @source.setter\n def source(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_out_edge(self)\n self._source = f\n\n @source.deleter\n def source(self) -> None:\n self._source.remove_out_edge(self)\n self._source = None\n\n @property\n def source_id(self) -> Union[int, Any]:\n \"\"\"The ID of the source object or 1 if no source is set\n\n Returns:\n int: Source object ID\n \"\"\"\n if self.source is not None:\n return self.source.id\n else:\n return 1\n\n # Target\n @property\n def target(self) -> Optional[DiagramBase]:\n \"\"\"The target object of the edge. Automatically adds the edge to the object when set and removes it when deleted.\n\n Returns:\n BaseDiagram: target object of the edge\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, f: Optional[DiagramBase]) -> None:\n if f is not None:\n f.add_in_edge(self)\n self._target = f\n\n @target.deleter\n def target(self) -> None:\n self._target.remove_in_edge(self)\n self._target = None\n\n @property\n def target_id(self) -> Union[int, Any]:\n \"\"\"The ID of the target object or 1 if no target is set\n\n Returns:\n int: Target object ID\n \"\"\"\n if self.target is not None:\n return self.target.id\n else:\n return 1\n\n def add_point(self, x: int, y: int) -> None:\n \"\"\"Add a point to the edge\n\n Args:\n x (int): The x coordinate of the point in pixels\n y (int): The y coordinate of the point in pixels\n \"\"\"\n self.geometry.points.append(Point(x=x, y=y))\n\n def add_point_pos(self, position: Tuple[int, int]) -> None:\n \"\"\"Add a point to the edge by position tuple\n\n Args:\n position (tuple): A tuple of ints describing the x and y coordinates in pixels\n \"\"\"\n self.geometry.points.append(Point(x=position[0], y=position[1]))\n\n ###########################################################\n # Style properties\n ###########################################################\n\n @property\n def style_attributes(self) -> List[str]:\n \"\"\"The style attributes to add to the style tag in the XML\n\n Returns:\n list: A list of style attributes\n \"\"\"\n return [\n \"rounded\",\n \"sketch\",\n \"shadow\",\n \"flowAnimation\",\n \"jettySize\",\n \"entryX\",\n \"entryY\",\n \"entryDx\",\n \"entryDy\",\n \"exitX\",\n \"exitY\",\n \"exitDx\",\n \"exitDy\",\n \"startArrow\",\n \"endArrow\",\n \"startFill\",\n \"endFill\",\n \"strokeColor\",\n \"strokeWidth\",\n \"fillColor\",\n \"jumpStyle\",\n \"jumpSize\",\n \"targetPerimeterSpacing\",\n \"sourcePerimeterSpacing\",\n \"endSize\",\n \"startSize\",\n \"opacity\",\n ]\n\n @property\n def baseStyle(self) -> Optional[str]:\n \"\"\"Generates the baseStyle string from the connection style, waypoint style, pattern style, and base style string.\n\n Returns:\n str: Concatenated baseStyle string\n \"\"\"\n style_str: List[str] = []\n connection_style: Optional[str] = style_str_from_dict(\n connection_db[self.connection]\n )\n if connection_style is not None and connection_style != \"\":\n style_str.append(connection_style)\n\n waypoint_style: Optional[str] = style_str_from_dict(\n waypoints_db[self.waypoints]\n )\n if waypoint_style is not None and waypoint_style != \"\":\n style_str.append(waypoint_style)\n\n pattern_style: Optional[str] = style_str_from_dict(pattern_db[self.pattern])\n if pattern_style is not None and pattern_style != \"\":\n style_str.append(pattern_style)\n\n if len(style_str) == 0:\n return None\n else:\n return \";\".join(style_str)\n\n @property\n def startArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the source\n\n Returns:\n str: The source edge graphic\n \"\"\"\n return self.line_end_source\n\n @startArrow.setter\n def startArrow(self, val: Optional[str]) -> None:\n self.line_end_source = val\n\n @property\n def startFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the source should be filled\n\n Returns:\n bool: The source graphic fill\n \"\"\"\n if line_ends_db[self.line_end_source][\"fillable\"]:\n return self.endFill_source\n else:\n return None\n\n @property\n def endArrow(self) -> Optional[str]:\n \"\"\"What graphic the edge should be rendered with at the target\n\n Returns:\n str: The target edge graphic\n \"\"\"\n return self.line_end_target\n\n @endArrow.setter\n def endArrow(self, val: Optional[str]) -> None:\n self.line_end_target = val\n\n @property\n def endFill(self) -> Optional[bool]:\n \"\"\"Whether the graphic at the target should be filled\n\n Returns:\n bool: The target graphic fill\n \"\"\"\n if line_ends_db[self.line_end_target][\"fillable\"]:\n return self.endFill_target\n else:\n return None\n\n # Base Line Style\n\n # Waypoints\n @property\n def waypoints(self) -> str:\n \"\"\"The waypoint style. Checks if the passed in value is in the TOML database of waypoints before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the waypoints\n \"\"\"\n return self._waypoints\n\n @waypoints.setter\n def waypoints(self, value: str) -> None:\n if value in waypoints_db.keys():\n self._waypoints = value\n else:\n raise ValueError(\"{0} is not an allowed value of waypoints\")\n\n # Connection\n @property\n def connection(self) -> str:\n \"\"\"The connection style. Checks if the passed in value is in the TOML database of connections before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the connections\n \"\"\"\n return self._connection\n\n @connection.setter\n def connection(self, value: str) -> None:\n if value in connection_db.keys():\n self._connection = value\n else:\n raise ValueError(\"{0} is not an allowed value of connection\".format(value))\n\n # Pattern\n @property\n def pattern(self) -> str:\n \"\"\"The pattern style. Checks if the passed in value is in the TOML database of patterns before setting and throws a ValueError if not.\n\n Returns:\n str: The style of the patterns\n \"\"\"\n return self._pattern\n\n @pattern.setter\n def pattern(self, value: str) -> None:\n if value in pattern_db.keys():\n self._pattern = value\n else:\n raise ValueError(\"{0} is not an allowed value of pattern\")\n\n # Color properties (enforce value)\n ## strokeColor\n @property\n def strokeColor(self) -> Optional[str]:\n return self._strokeColor\n\n @strokeColor.setter\n def strokeColor(self, value: Optional[str]) -> None:\n self._strokeColor = color_input_check(value)\n\n @strokeColor.deleter\n def strokeColor(self) -> None:\n self._strokeColor = None\n\n ## strokeWidth\n @property\n def strokeWidth(self) -> Optional[int]:\n return self._strokeWidth\n\n @strokeWidth.setter\n def strokeWidth(self, value: Optional[int]) -> None:\n self._strokeWidth = width_input_check(value)\n\n @strokeWidth.deleter\n def strokeWidth(self) -> None:\n self._strokeWidth = None\n\n # fillColor\n @property\n def fillColor(self) -> Optional[str]:\n return self._fillColor\n\n @fillColor.setter\n def fillColor(self, value: Optional[str]) -> None:\n self._fillColor = color_input_check(value)\n\n @fillColor.deleter\n def fillColor(self) -> None:\n self._fillColor = None\n\n # Jump style (enforce value)\n @property\n def jumpStyle(self) -> Optional[str]:\n return self._jumpStyle\n\n @jumpStyle.setter\n def jumpStyle(self, value: Optional[str]) -> None:\n if value in [None, \"arc\", \"gap\", \"sharp\", \"line\"]:\n self._jumpStyle = value\n else:\n raise ValueError(f\"'{value}' is not a permitted jumpStyle value!\")\n\n @jumpStyle.deleter\n def jumpStyle(self) -> None:\n self._jumpStyle = None\n\n ###########################################################\n # XML Generation\n ###########################################################\n\n @property\n def label(self) -> Optional[str]:\n \"\"\"The text to place on the label, aka its value.\"\"\"\n return self.value\n\n @label.setter\n def label(self, value: Optional[str]) -> None:\n self.value = value\n\n @label.deleter\n def label(self) -> None:\n self.value = None\n\n @property\n def label_offset(self) -> Optional[int]:\n \"\"\"How far the label is offset away from the axis of the edge in pixels\"\"\"\n return self.geometry.y\n\n @label_offset.setter\n def label_offset(self, value: Optional[int]) -> None:\n self.geometry.y = value\n\n @label_offset.deleter\n def label_offset(self) -> None:\n self.geometry.y = None\n\n @property\n def label_position(self) -> Optional[float]:\n \"\"\"Where along the edge the label is positioned. -1 is the source, 1 is the target, 0 is the center.\"\"\"\n return self.geometry.x\n\n @label_position.setter\n def label_position(self, value: Optional[float]) -> None:\n self.geometry.x = value\n\n @label_position.deleter\n def label_position(self) -> None:\n self.geometry.x = None\n\n @property\n def xml(self) -> str:\n \"\"\"The opening and closing XML tags with the styling attributes included.\n\n Returns:\n str: _description_\n \"\"\"\n tag: str = (\n self.xml_open_tag + \"\\n \" + self.geometry.xml + \"\\n\" + self.xml_close_tag\n )\n return tag", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 20434}, "tests/xml_base_test.py::144": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_translate_txt_complex_replacement", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/diagram_tests/legend_test.py::61": {"resolved_imports": ["src/drawpyo/diagram_types/legend.py", "src/drawpyo/diagram/text_format.py", "src/drawpyo/utils/standard_colors.py", "src/drawpyo/utils/color_scheme.py", "src/drawpyo/page.py", "src/drawpyo/diagram/objects.py"], "used_names": ["Legend", "pytest"], "enclosing_function": "test_requires_non_empty_mapping", "extracted_code": "# Source: src/drawpyo/diagram_types/legend.py\nclass Legend:\n \"\"\"A simple color/label legend diagram.\"\"\"\n\n # Layout constants\n COLOR_BOX_SIZE = 20\n COLOR_TEXT_GAP = 10\n ROW_GAP = 8\n TITLE_BOTTOM_MARGIN = 20\n BACKGROUND_PADDING = 15\n\n def __init__(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]], **kwargs\n ):\n \"\"\"\n Args:\n mapping (dict[str, StandardColor, ColorScheme]): Mapping of labels to colors.\n\n Keyword Args:\n position (tuple[int, int]): Top-left diagram position. Default: (0, 0)\n title (str): Optional title.\n title_text_format (TextFormat): Formatting for the title.\n label_text_format (TextFormat): Formatting for labels.\n glass (bool): Whether color boxes have a glass effect. Default: False\n rounded (bool): Whether color boxes have rounded corners. Default: False\n background_color (str | StandardColor): Optional background fill color.\n \"\"\"\n\n if not isinstance(mapping, dict) or not mapping:\n raise ValueError(\"Mapping must be a non-empty dict.\")\n\n self._mapping: dict[str, Union[str, StandardColor, ColorScheme]] = (\n mapping.copy()\n )\n\n # Position\n self._position: tuple[int, int] = kwargs.get(\"position\", (0, 0))\n\n # Title\n self._title: Optional[str] = kwargs.get(\"title\")\n\n # Text formats\n self._title_text_format: TextFormat = deepcopy(\n kwargs.get(\"title_text_format\", TextFormat())\n )\n self._label_text_format: TextFormat = deepcopy(\n kwargs.get(\"label_text_format\", TextFormat())\n )\n\n # Color box styles\n self._glass: Optional[bool] = kwargs.get(\"glass\", False)\n self._rounded: Optional[bool] = kwargs.get(\"rounded\", False)\n\n # Background\n self._background_color: Optional[Union[str, StandardColor]] = kwargs.get(\n \"background_color\"\n )\n\n self._group = Group()\n self._build()\n\n # -----------------------------------------------------\n # Public methods\n # -----------------------------------------------------\n\n @property\n def group(self) -> Group:\n return self._group\n\n @property\n def position(self) -> tuple[int, int]:\n return self._position\n\n def update_mapping(\n self, mapping: dict[str, Union[str, StandardColor, ColorScheme]]\n ):\n self._mapping = mapping.copy()\n self._rebuild()\n\n def move(self, new_position: tuple[int, int]):\n new_x, new_y = new_position\n old_x, old_y = self._position\n dx = new_x - old_x\n dy = new_y - old_y\n\n for obj in self._group.objects:\n x, y = obj.position\n obj.position = (x + dx, y + dy)\n\n self._position = new_position\n self._group.update_geometry()\n\n def add_to_page(self, page: Page):\n for obj in self._group.objects:\n page.add_object(obj)\n\n # -----------------------------------------------------\n # Private methods\n # -----------------------------------------------------\n\n def _rebuild(self):\n self._group.objects.clear()\n self._build()\n\n def _build(self):\n x, y = self._position\n\n title_offset = (\n (self._title_text_format.fontSize or 16) + self.TITLE_BOTTOM_MARGIN\n if self._title\n else 0\n )\n\n bg_width, bg_height = self._compute_background_dimensions(title_offset)\n\n if self._background_color:\n self._add_background(bg_width, bg_height, title_offset)\n\n if self._title:\n self._add_title()\n\n current_y = y + title_offset\n\n # Create rows\n for label, color in self._mapping.items():\n self._add_row(label, color, current_y)\n current_y += self.COLOR_BOX_SIZE + self.ROW_GAP\n\n self._group.update_geometry()\n\n def _compute_background_dimensions(self, title_offset: int) -> tuple[int, int]:\n \"\"\"Compute background size dynamically based on label lengths.\"\"\"\n\n # Estimate text width\n max_text_len = max(len(label) for label in self._mapping)\n approx_text_width = max_text_len * 8\n\n width = (\n self.COLOR_BOX_SIZE\n + self.COLOR_TEXT_GAP\n + approx_text_width\n + (2 * self.BACKGROUND_PADDING)\n )\n height = (\n title_offset\n + len(self._mapping) * (self.COLOR_BOX_SIZE + self.ROW_GAP)\n - self.ROW_GAP\n + (2 * self.BACKGROUND_PADDING)\n )\n\n return width, height\n\n def _add_background(self, w: int, h: int, title_offset: int):\n x, y = self._position\n bg = Object(\n value=\"\",\n position=(x - self.BACKGROUND_PADDING, y - self.BACKGROUND_PADDING),\n width=w,\n height=h,\n fillColor=self._background_color,\n strokeColor=None,\n )\n self._group.add_object(bg)\n\n def _add_title(self):\n x, y = self._position\n text_h = (self._title_text_format.fontSize or 16) + 4\n\n title_obj = Object(\n value=self._title,\n position=(x, y),\n width=200,\n height=text_h,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n\n title_obj.text_format = deepcopy(self._title_text_format)\n title_obj.text_format.align = \"left\"\n title_obj.text_format.verticalAlign = \"top\"\n\n self._group.add_object(title_obj)\n\n def _add_row(\n self, label: str, color: Union[str, StandardColor, ColorScheme], y: int\n ):\n x, _ = self._position\n\n # Color square\n color_box = Object(\n value=\"\",\n position=(x, y),\n width=self.COLOR_BOX_SIZE,\n height=self.COLOR_BOX_SIZE,\n fillColor=None if isinstance(color, ColorScheme) else color,\n color_scheme=(color if isinstance(color, ColorScheme) else None),\n rounded=self._rounded,\n glass=self._glass,\n )\n self._group.add_object(color_box)\n\n # Text label\n label_obj = Object(\n value=label,\n position=(x + self.COLOR_BOX_SIZE + self.COLOR_TEXT_GAP, y),\n width=200,\n height=self.COLOR_BOX_SIZE,\n fillColor=\"none\",\n strokeColor=\"none\",\n )\n label_obj.text_format = deepcopy(self._label_text_format)\n label_obj.text_format.align = \"left\"\n label_obj.text_format.verticalAlign = \"middle\"\n\n self._group.add_object(label_obj)\n\n def __repr__(self):\n return f\"Legend(items={len(self._mapping)}, position={self._position})\"", "n_imports_parsed": 7, "n_files_resolved": 6, "n_chars_extracted": 6766}, "tests/page_test.py::167": {"resolved_imports": ["src/drawpyo/__init__.py"], "used_names": ["drawpyo"], "enclosing_function": "test_custom_grid_size", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}}}