defcon icon indicating copy to clipboard operation
defcon copied to clipboard

Color object is not equal with the assignet value

Open Eigi opened this issue 6 years ago • 2 comments

Hello, I try to work with named colors as used in HTML/CSS. My problem ist best shown in the following sample script:

from defcon.objects.glyph import Glyph
from fontParts.world import RGlyph

azure = 0xF0FFFF

def rgb_int_to_tuple(rgb_int, alpha=1):
    r = ((rgb_int >> 16) & 255) / 255
    g = ((rgb_int >> 8) & 255) / 255
    b = (rgb_int & 255) / 255
    return (r, g, b, alpha)

azure_tuple = rgb_int_to_tuple(azure)
print("azure_tuple : ", azure_tuple)

# > azure_tuple :  (0.9411764705882353, 1.0, 1.0, 1)


# Test with defcon glyph =======================================================
glyph = Glyph()
glyph.markColor = azure_tuple
print("glyph.markColor : ", glyph.markColor)
print("tuple(glyph.markColor) : ", tuple(glyph.markColor))
print("tuple(glyph.markColor) == azure_tuple : ", tuple(glyph.markColor) == azure_tuple)

# > glyph.markColor :  0.94118,1,1,1
# > tuple(glyph.markColor) :  (0.94118, 1, 1, 1)
# > tuple(glyph.markColor) == azure_tuple :  False


#Test with fontParts glyph =====================================================
rglyph = RGlyph()
rglyph.markColor = azure_tuple
print("rglyph.markColor : ", rglyph.markColor)
print("rglyph.markColor == azure_tuple : ", rglyph.markColor == azure_tuple)

# > rglyph.markColor :  (0.94118, 1.0, 1.0, 1.0)
# > rglyph.markColor == azure_tuple :  False

I want to mark glyphs with a specific color and later I want to find the glyphs which are marked with that color. But as illustrated above, this does not work as expected. I suspect the root of the problem is in the "stringification" of the defcon Color object, which rounds the color components to 5 decimal places. Therefore the assigned value does not equal the value which stored in the object and equality test with the assigned value fails.

Eigi avatar May 05 '19 14:05 Eigi

I suggest to add the following method to ColorTest in defcon.test.objects.test_color:

def test_from_tuple_2(self):
    testTuple = (0xF0/255, 0x0F/255, 0x80/255, 0x08/255)
    self.assertEqual(tuple(Color(testTuple)), testTuple)

Best Eigi

Eigi avatar May 05 '19 15:05 Eigi

If you want to look up the color afterwards for example for sorting glyphs it is best to compare mark colors with Color objects:

from defcon import Glyph, Color
# create a color
c = Color((1, 1, .123456789, .3))
# create a glyph
glyph = Glyph()
# set a mark color
glyph.markColor = c
# compare
print(glyph.markColor == c)
print(glyph.markColor == Color((1, 1, .123456789, .3))

so far I as I can see the color object is well enough tested https://github.com/robotools/defcon/blob/master/Lib/defcon/test/objects/test_color.py

if not a PR would be nice

thanks!

typemytype avatar May 07 '19 14:05 typemytype