• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import unittest
2
3try:
4    from fontTools.pens.cocoaPen import CocoaPen
5    from AppKit import NSBezierPathElementMoveTo, NSBezierPathElementLineTo
6    from AppKit import NSBezierPathElementCurveTo, NSBezierPathElementClosePath
7
8    PATH_ELEMENTS = {
9        # NSBezierPathElement key      desc
10        NSBezierPathElementMoveTo:    'moveto',
11        NSBezierPathElementLineTo:    'lineto',
12        NSBezierPathElementCurveTo:   'curveto',
13        NSBezierPathElementClosePath: 'close',
14    }
15
16    PYOBJC_AVAILABLE = True
17except ImportError:
18    PYOBJC_AVAILABLE = False
19
20
21def draw(pen):
22    pen.moveTo((50, 0))
23    pen.lineTo((50, 500))
24    pen.lineTo((200, 500))
25    pen.curveTo((350, 500), (450, 400), (450, 250))
26    pen.curveTo((450, 100), (350, 0), (200, 0))
27    pen.closePath()
28
29
30def cocoaPathToString(path):
31    num_elements = path.elementCount()
32    output = []
33    for i in range(num_elements - 1):
34        elem_type, elem_points = path.elementAtIndex_associatedPoints_(i)
35        elem_type = PATH_ELEMENTS[elem_type]
36        path_points = " ".join([f"{p.x} {p.y}" for p in elem_points])
37        output.append(f"{elem_type} {path_points}")
38    return " ".join(output)
39
40
41@unittest.skipUnless(PYOBJC_AVAILABLE, "pyobjc not installed")
42class CocoaPenTest(unittest.TestCase):
43    def test_draw(self):
44        pen = CocoaPen(None)
45        draw(pen)
46        self.assertEqual(
47            "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 ",
48            cocoaPathToString(pen.path)
49        )
50
51    def test_empty(self):
52        pen = CocoaPen(None)
53        self.assertEqual("", cocoaPathToString(pen.path))
54
55
56if __name__ == '__main__':
57    import sys
58    sys.exit(unittest.main())
59