Rewrite colors into shortest possible name

Improve the code for rewriting colors into recognising that some
colors are shorter by name.  This commit enables scour to rewrite
`rgb(255, 0, 0)` into `red` which is slightly shorter than `#f00`
(ditto for `tan` and `pink`).

When the color name ties in length with the hexcode, then scour will
leave it as-is if the input file used a variant of same length
(e.g. `blue`, `cyan` and `aqua` will be left as-is).  But if scour is
rewriting the color code, it will prefer the hex code variant.

Signed-off-by: Niels Thykier <niels@thykier.net>
This commit is contained in:
Niels Thykier 2021-02-23 18:35:57 +00:00
parent 7a83e7148d
commit 551c88754e
No known key found for this signature in database
GPG key ID: A65B78DBE67C7AAC
3 changed files with 248 additions and 166 deletions

View file

@ -1211,7 +1211,7 @@ class TranslateRGBPctIntoHex(unittest.TestCase):
class TranslateColorNamesIntoHex(unittest.TestCase):
def runTest(self):
elem = scourXmlFile('unittests/color-formats.svg').getElementsByTagNameNS(SVGNS, 'rect')[0]
elem = scourXmlFile('unittests/color-formats.svg').getElementById('rect')
self.assertEqual(elem.getAttribute('stroke'), '#a9a9a9',
'Not converting standard color names into hex')
@ -1232,6 +1232,22 @@ class TranslateLongHexColorIntoShortHex(unittest.TestCase):
'Not converting long hex color into short hex')
class TranslateColorIntoNameIfShorter(unittest.TestCase):
def runTest(self):
short = scourXmlFile('unittests/color-formats.svg').getElementById('short_color')
tied = scourXmlFile('unittests/color-formats.svg').getElementById('tied_color')
self.assertEqual(short.getAttribute('fill'), 'red',
'Not converting color into color name')
self.assertEqual(short.getAttribute('stroke'), 'red',
'Not converting color into color name')
self.assertEqual(tied.getAttribute('fill'), 'blue',
'Not keeping the current name when it ties with the shortest match')
self.assertEqual(tied.getAttribute('stroke'), '#00f',
'Not using color hex code when rewriting color where len(hex_code) == len(name)')
class DoNotConvertShortColorNames(unittest.TestCase):
def runTest(self):