Skip to content

Commit

Permalink
Support specifying hex colors where no color name is needed
Browse files Browse the repository at this point in the history
This was requested by designer2k2 in #219 for bgcolor usage.
It has also been discussed in #135.

The input validation is more detailed to help the user identifying
and locating invalid values. The wire color padding is now done on
the output to cover different input alternatives.
  • Loading branch information
kvid authored and formatc1702 committed Sep 28, 2021
1 parent 166ab2f commit b3fdd48
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
3 changes: 3 additions & 0 deletions docs/syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,9 @@ The following colors are understood:
<!-- color list generated with a helper script: -->
<!-- https://gist.github.com/formatc1702/3c93fb4c5e392364899283f78672b952 -->

Unless the color also is displayed as a non-hexadecimal text in the diagram,
it is possible to specify colors as hexadecimal RGB values, e.g. `#112233`.

## Cable color codes

Supported color codes:
Expand Down
36 changes: 25 additions & 11 deletions src/wireviz/wv_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,23 +107,37 @@

color_default = '#ffffff'

_hex_digits = set('0123456789abcdefABCDEF')

def get_color_hex(input, pad=False):
"""Return list of hex colors from either a string of color names or :-separated hex colors."""
if input is None or input == '':
return [color_default]
elif input[0] == '#': # Hex color(s)
output = input.split(':')
for i, c in enumerate(output):
if c[0] != '#' or not all(d in _hex_digits for d in c[1:]):
if c != input:
c += f' in input: {input}'
print(f'Invalid hex color: {c}')
output[i] = color_default
else: # Color name(s)
def lookup(c: str) -> str:
try:
return _color_hex[c]
except KeyError:
if c != input:
c += f' in input: {input}'
print(f'Unknown color name: {c}')
return color_default

if len(input) == 4: # give wires with EXACTLY 2 colors that striped/banded look
padded = input + input[:2]
elif pad and len(input) == 2: # hacky style fix: give single color wires a triple-up so that wires are the same size
padded = input + input + input
else:
padded = input
output = [lookup(input[i:i + 2]) for i in range(0, len(input), 2)]

if len(output) == 2: # Give wires with EXACTLY 2 colors that striped look.
output += output[:1]
elif pad and len(output) == 1: # Hacky style fix: Give single color wires
output *= 3 # a triple-up so that wires are the same size.

try:
output = [_color_hex[padded[i:i + 2]] for i in range(0, len(padded), 2)]
except KeyError:
print(f'Unknown color specified: {input}')
output = [color_default]
return output


Expand Down

0 comments on commit b3fdd48

Please sign in to comment.