diff --git a/docs/advanced_image_usage.md b/docs/advanced_image_usage.md new file mode 100644 index 00000000..5fd4288f --- /dev/null +++ b/docs/advanced_image_usage.md @@ -0,0 +1,61 @@ +# Advanced Image Usage + +In rare cases when the [ordinary image scaling functionality](syntax.md#images) is insufficient, a couple of extra optional image attributes can be set to offer extra image cell space and scaling functionality when combined with the image dimension attributes `width` and `height`, but in most cases their default values below are sufficient: +- `scale: ` (how an image will use the available cell space) is default `false` if no dimension is set, or `true` if only one dimension is set, or `both` if both dimensions are set. +- `fixedsize: ` (scale to fixed size or expand to minimum size) is default `false` when no dimension is set or if a `scale` value is set, and `true` otherwise. +- When `fixedsize` is true and only one dimension is set, then the other dimension is calculated using the image aspect ratio. If reading the aspect ratio fails, then 1:1 ratio is assumed. + +See explanations of all supported values for these attributes in subsections below. + +## The effect of `fixedsize` boolean values + +- When `false`, any `width` or `height` values are _minimum_ values used to expand the image cell size for more available space, but cell contents or other size demands in the table might expand this cell even more than specified by `width` or `height`. +- When `true`, both `width` and `height` values are required by Graphwiz and specify the fixed size of the image cell, distorting any image inside if it don't fit. Any borders are normally drawn around the fixed size, and therefore, WireViz enclose the image cell in an extra table without borders when `fixedsize` is true to keep the borders around the outer non-fixed cell. + +## The effect of `scale` string values: + +- When `false`, the image is not scaled. +- When `true`, the image is scaled proportionally to fit within the available image cell space. +- When `width`, the image width is expanded (height is normally unchanged) to fill the available image cell space width. +- When `height`, the image height is expanded (width is normally unchanged) to fill the available image cell space height. +- When `both`, both image width and height are expanded independently to fill the available image cell space. + +In all cases (except `true`) the image might get distorted when a specified fixed image cell size limits the available space to less than what an unscaled image needs. + +In the WireViz diagrams there are no other space demanding cells in the same row, and hence, there are never extra available image cell space height unless a greater image cell `height` also is set. + +## Usage examples + +All examples of `image` attribute combinations below also require the mandatory `src` attribute to be set. + +- Expand the image proportionally to fit within a minimum height and the node width: +```yaml + height: 100 # Expand image cell to this minimum height + fixedsize: false # Avoid scaling to a fixed size + # scale default value is true in this case +``` + +- Increase the space around the image by expanding the image cell space (width and/or height) to a larger value without scaling the image: +```yaml + width: 200 # Expand image cell to this minimum width + height: 100 # Expand image cell to this minimum height + scale: false # Avoid scaling the image + # fixedsize default value is false in this case +``` + +- Stretch the image width to fill the available space in the node: +```yaml + scale: width # Expand image width to fill the available image cell space + # fixedsize default value is false in this case +``` + +- Stretch the image height to a minimum value: +```yaml + height: 100 # Expand image cell to this minimum height + scale: height # Expand image height to fill the available image cell space + # fixedsize default value is false in this case +``` + +## How Graphviz support this image scaling + +The connector and cable nodes are rendered using a HTML `` containing an image cell `') elif row is not None: @@ -53,6 +55,30 @@ def nested_html_table(rows): html.append('
` with `width`, `height`, and `fixedsize` attributes containing an image `` with `src` and `scale` attributes. See also the [Graphviz doc](https://graphviz.org/doc/info/shapes.html#html), but note that WireViz uses default values as described above. diff --git a/examples/ex08.yml b/examples/ex08.yml index 2195c4a0..eea3976a 100644 --- a/examples/ex08.yml +++ b/examples/ex08.yml @@ -1,4 +1,5 @@ # contributed by @cocide +# and later extended to include images connectors: Key: @@ -7,14 +8,22 @@ connectors: pins: [T, R, S] pinlabels: [Dot, Dash, Ground] show_pincount: false + image: + src: resources/stereo-phone-plug-TRS.png + caption: Tip, Ring, and Sleeve cables: W1: gauge: 24 AWG length: 0.2 + color: BK # Cable jacket color color_code: DIN wirecount: 3 - shield: true + shield: SN # Matching the shield color in the image + image: + src: resources/cable-WH+BN+GN+shield.png + height: 70 # Scale the image size slightly down + caption: Cross-section connections: - diff --git a/examples/resources/cable-WH+BN+GN+shield.png b/examples/resources/cable-WH+BN+GN+shield.png new file mode 100644 index 00000000..f854aeae Binary files /dev/null and b/examples/resources/cable-WH+BN+GN+shield.png differ diff --git a/examples/resources/stereo-phone-plug-TRS.png b/examples/resources/stereo-phone-plug-TRS.png new file mode 100644 index 00000000..6ac1274f Binary files /dev/null and b/examples/resources/stereo-phone-plug-TRS.png differ diff --git a/requirements.txt b/requirements.txt index 93394812..92620aea 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ . graphviz +pillow pyyaml setuptools \ No newline at end of file diff --git a/setup.py b/setup.py index 09621bb7..60b1dfbe 100644 --- a/setup.py +++ b/setup.py @@ -23,6 +23,7 @@ def read(fname): long_description_content_type='text/markdown', install_requires=[ 'pyyaml', + 'pillow', 'graphviz', ], license='GPLv3', diff --git a/src/wireviz/DataClasses.py b/src/wireviz/DataClasses.py index 6b3b1e36..3ad84d21 100644 --- a/src/wireviz/DataClasses.py +++ b/src/wireviz/DataClasses.py @@ -2,11 +2,48 @@ # -*- coding: utf-8 -*- from typing import Optional, List, Any, Union -from dataclasses import dataclass, field -from wireviz.wv_helper import int2tuple +from dataclasses import dataclass, field, InitVar +from pathlib import Path +from wireviz.wv_helper import int2tuple, aspect_ratio from wireviz import wv_colors +@dataclass +class Image: + gv_dir: InitVar[Path] # Directory of .gv file injected as context during parsing + # Attributes of the image object : + src: str + scale: Optional[str] = None # false | true | width | height | both + # Attributes of the image cell containing the image: + width: Optional[int] = None + height: Optional[int] = None + fixedsize: Optional[bool] = None + # Contents of the text cell just below the image cell: + caption: Optional[str] = None + # See also HTML doc at https://graphviz.org/doc/info/shapes.html#html + + def __post_init__(self, gv_dir): + + if self.fixedsize is None: + # Default True if any dimension specified unless self.scale also is specified. + self.fixedsize = (self.width or self.height) and self.scale is None + + if self.scale is None: + self.scale = "false" if not self.width and not self.height \ + else "both" if self.width and self.height \ + else "true" # When only one dimension is specified. + + if self.fixedsize: + # If only one dimension is specified, compute the other + # because Graphviz requires both when fixedsize=True. + if self.height: + if not self.width: + self.width = self.height * aspect_ratio(gv_dir.joinpath(self.src)) + else: + if self.width: + self.height = self.width / aspect_ratio(gv_dir.joinpath(self.src)) + + @dataclass class Connector: name: str @@ -18,6 +55,7 @@ class Connector: type: Optional[str] = None subtype: Optional[str] = None pincount: Optional[int] = None + image: Optional[Image] = None notes: Optional[str] = None pinlabels: List[Any] = field(default_factory=list) pins: List[Any] = field(default_factory=list) @@ -29,6 +67,10 @@ class Connector: loops: List[Any] = field(default_factory=list) def __post_init__(self): + + if isinstance(self.image, dict): + self.image = Image(**self.image) + self.ports_left = False self.ports_right = False self.visible_pins = {} @@ -91,6 +133,7 @@ class Cable: color: Optional[str] = None wirecount: Optional[int] = None shield: bool = False + image: Optional[Image] = None notes: Optional[str] = None colors: List[Any] = field(default_factory=list) color_code: Optional[str] = None @@ -99,6 +142,9 @@ class Cable: def __post_init__(self): + if isinstance(self.image, dict): + self.image = Image(**self.image) + if isinstance(self.gauge, str): # gauge and unit specified try: g, u = self.gauge.split(' ') diff --git a/src/wireviz/Harness.py b/src/wireviz/Harness.py index af7946e3..e701425a 100644 --- a/src/wireviz/Harness.py +++ b/src/wireviz/Harness.py @@ -8,7 +8,7 @@ from wireviz.wv_helper import awg_equiv, mm2_equiv, tuplelist2tsv, \ nested_html_table, flatten2d, index_if_list, html_line_breaks, \ graphviz_line_breaks, remove_line_breaks, open_file_read, open_file_write, \ - manufacturer_info_field + html_image, html_caption, manufacturer_info_field from collections import Counter from typing import List from pathlib import Path @@ -98,6 +98,8 @@ def create_graph(self) -> Graph: f'{connector.pincount}-pin' if connector.show_pincount else None, connector.color, '' if connector.color else None], '' if connector.style != 'simple' else None, + [html_image(connector.image)], + [html_caption(connector.image)], [html_line_breaks(connector.notes)]] html.extend(nested_html_table(rows)) @@ -173,6 +175,8 @@ def create_graph(self) -> Graph: f'{cable.length} m' if cable.length > 0 else None, cable.color, '' if cable.color else None], '', + [html_image(cable.image)], + [html_caption(cable.image)], [html_line_breaks(cable.notes)]] html.extend(nested_html_table(rows)) diff --git a/src/wireviz/wireviz.py b/src/wireviz/wireviz.py index 3adc0782..5543e099 100755 --- a/src/wireviz/wireviz.py +++ b/src/wireviz/wireviz.py @@ -44,6 +44,11 @@ def parse(yaml_input: str, file_out: (str, Path) = None, return_types: (None, st if len(yaml_data[sec]) > 0: if ty == dict: for key, attribs in yaml_data[sec].items(): + # The Image dataclass might need to open an image file with a relative path. + image = attribs.get('image') + if isinstance(image, dict): + image['gv_dir'] = Path(file_out if file_out else '').parent # Inject context + if sec == 'connectors': if not attribs.get('autogenerate', False): harness.add_connector(name=key, **attribs) diff --git a/src/wireviz/wv_helper.py b/src/wireviz/wv_helper.py index 418060d2..32b8fb6b 100644 --- a/src/wireviz/wv_helper.py +++ b/src/wireviz/wv_helper.py @@ -34,6 +34,7 @@ def nested_html_table(rows): # input: list, each item may be scalar or list # output: a parent table with one child table per parent item that is list, and one cell per parent item that is scalar # purpose: create the appearance of one table, where cell widths are independent between rows + # attributes in any leading inside a list are injected into to the preceeding tag html = [] html.append('') for row in rows: @@ -43,7 +44,8 @@ def nested_html_table(rows): html.append('
') for cell in row: if cell is not None: - html.append(f' ') + # Inject attributes to the preceeding '.replace('>
{cell} tag where needed + html.append(f' {cell}
') html.append('
') return html +def html_image(image): + if not image: + return None + # The leading attributes belong to the preceeding tag. See where used below. + html = f'{html_size_attr(image)}>' + if image.fixedsize: + # Close the preceeding tag and enclose the image cell in a table without + # borders to avoid narrow borders when the fixed width < the node width. + html = f'''> + + +
+ ''' + return f'''{html_line_breaks(image.caption)}' if image and image.caption else None + +def html_size_attr(image): + # Return Graphviz HTML attributes to specify minimum or fixed size of a TABLE or TD object + return ((f' width="{image.width}"' if image.width else '') + + (f' height="{image.height}"' if image.height else '') + + ( ' fixedsize="true"' if image.fixedsize else '')) if image else '' + def expand(yaml_data): # yaml_data can be: @@ -132,6 +158,20 @@ def open_file_write(filename): def open_file_append(filename): return open(filename, 'a', encoding='UTF-8') + +def aspect_ratio(image_src): + try: + from PIL import Image + image = Image.open(image_src) + if image.width > 0 and image.height > 0: + return image.width / image.height + print(f'aspect_ratio(): Invalid image size {image.width} x {image.height}') + # ModuleNotFoundError and FileNotFoundError are the most expected, but all are handled equally. + except Exception as error: + print(f'aspect_ratio(): {type(error).__name__}: {error}') + return 1 # Assume 1:1 when unable to read actual image size + + def manufacturer_info_field(manufacturer, mpn): if manufacturer or mpn: return f'{manufacturer if manufacturer else "MPN"}{": " + str(mpn) if mpn else ""}'