aboutsummaryrefslogtreecommitdiff
path: root/Tests/pens/cocoaPen_test.py
blob: 11077c0b506150857197b599f474b3c5426b3861 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import unittest

try:
    from fontTools.pens.cocoaPen import CocoaPen
    from AppKit import NSBezierPathElementMoveTo, NSBezierPathElementLineTo
    from AppKit import NSBezierPathElementCurveTo, NSBezierPathElementClosePath

    PATH_ELEMENTS = {
        # NSBezierPathElement key      desc
        NSBezierPathElementMoveTo:    'moveto',
        NSBezierPathElementLineTo:    'lineto',
        NSBezierPathElementCurveTo:   'curveto',
        NSBezierPathElementClosePath: 'close',
    }

    PYOBJC_AVAILABLE = True
except ImportError:
    PYOBJC_AVAILABLE = False


def draw(pen):
    pen.moveTo((50, 0))
    pen.lineTo((50, 500))
    pen.lineTo((200, 500))
    pen.curveTo((350, 500), (450, 400), (450, 250))
    pen.curveTo((450, 100), (350, 0), (200, 0))
    pen.closePath()


def cocoaPathToString(path):
    num_elements = path.elementCount()
    output = []
    for i in range(num_elements - 1):
        elem_type, elem_points = path.elementAtIndex_associatedPoints_(i)
        elem_type = PATH_ELEMENTS[elem_type]
        path_points = " ".join([f"{p.x} {p.y}" for p in elem_points])
        output.append(f"{elem_type} {path_points}")
    return " ".join(output)


@unittest.skipUnless(PYOBJC_AVAILABLE, "pyobjc not installed")
class CocoaPenTest(unittest.TestCase):
    def test_draw(self):
        pen = CocoaPen(None)
        draw(pen)
        self.assertEqual(
            "moveto 50.0 0.0 lineto 50.0 500.0 lineto 200.0 500.0 curveto 350.0 500.0 450.0 400.0 450.0 250.0 curveto 450.0 100.0 350.0 0.0 200.0 0.0 close ",
            cocoaPathToString(pen.path)
        )

    def test_empty(self):
        pen = CocoaPen(None)
        self.assertEqual("", cocoaPathToString(pen.path))


if __name__ == '__main__':
    import sys
    sys.exit(unittest.main())