Glyph SVG Syntax Representation ↩
This example shows how to register a defcon.Glyph
representation that outputs a svg syntax representation of the outline. The svg data is then sent to a HTMLView
stored in a WindowController
.
from defcon import Glyph, registerRepresentationFactory
from mojo.subscriber import (
Subscriber,
WindowController,
registerRoboFontSubscriber,
registerCurrentFontSubscriber,
unregisterRoboFontSubscriber,
unregisterCurrentFontSubscriber,
)
from ufo2svg.svgPathPen import SVGPathPen
from mojo.UI import HTMLView
from vanilla import Window
from mojo.roboFont import OpenWindow, CurrentGlyph
def svgFactory(glyph):
if not glyph.bounds:
return "<html></html>"
xMin, yMin, xMax, yMax = glyph.bounds
width = xMax-xMin
height = yMax-yMin
svgPen = SVGPathPen(glyph.layer)
glyph.draw(svgPen)
return f"""\
<html>
<svg width="{width}" height="{height}">
<path transform="scale(1 -1) translate(-{xMin} -{height+yMin})"
d="{svgPen.getCommands()}" />
</svg>
</html>
"""
class CurrentGlyphFollower(Subscriber):
debug = True
controller = None
def roboFontDidSwitchCurrentGlyph(self, info):
commands = svgFactory(info["glyph"])
self.controller.set(commands)
class CurrentGlyphObserver(Subscriber):
debug = True
controller = None
def currentGlyphDidChange(self, info):
commands = svgFactory(info["glyph"])
self.controller.set(commands)
class HTMLViewController(WindowController):
def build(self):
self.w = Window((1000, 1000), "HTML", minSize=(500, 200))
self.w.htmlView = HTMLView((0, 0, -0, -0))
self.w.open()
def started(self):
commands = svgFactory(CurrentGlyph())
self.set(commands)
CurrentGlyphFollower.controller = self
registerRoboFontSubscriber(CurrentGlyphFollower)
CurrentGlyphObserver.controller = self
registerCurrentFontSubscriber(CurrentGlyphObserver)
def destroy(self):
CurrentGlyphFollower.controller = None
unregisterRoboFontSubscriber(CurrentGlyphFollower)
CurrentGlyphObserver.controller = None
unregisterCurrentFontSubscriber(CurrentGlyphObserver)
def set(self, html):
self.w.htmlView.setHTML(html)
if __name__ == "__main__":
registerRepresentationFactory(Glyph, "svgRepresentation", svgFactory)
OpenWindow(HTMLViewController)