Custom Observers

An observer has to be subscribed to an specific event. When the event happens the observer will get a notification.

from mojo.events import addObserver

class myEventObserver:
    def __init__(self):
        addObserver(self, "myObserver", "mouseDown")

    def myObserver(self, info):
        print info #do something...

myEventObserver()

Real live example drawing a reference to the current glyph in the Glyph View using the unicode value of the glyph:

"""
An example script of adding an observers and do *something*

It draws a simple unicode reference of an existing installed font.
"""

from mojo.events import addObserver
from mojo.drawingTools import *

from lib.tools.misc import unicodeToChar


class DrawReferenceGlyph(object):

    def __init__(self):
        addObserver(self, "drawReferenceGlyph", "draw")

    def drawReferenceGlyph(self, info):
        glyph = info["glyph"]
        scaleValue = info["scale"]
        r = 0
        g = 0
        b = 0
        a = .5

        if glyph is not None and glyph.unicode is not None:
            t = unicodeToChar(glyph.unicode)
            save()
            translate(glyph.width + 10, 10)
            scale(scaleValue)
            font("Georgia", 20)
            stroke(None)
            fill(r, g, b, a)
            text(t, (0, 0))
            restore()


DrawReferenceGlyph()

More observers examples.

Observers

  • addObserver(observer, method, event)
    Adds an observer for an event to the observer method.
  • removeObserver(observer, event)
    Removes the observer for an event.

Events

Any observer can subscriber to these events. The callback receives a dictionary object containing additional objects related to the send event.

All notification dictionaries contains the following keys:

glyph the current/edited/active glyph
tool the current tool
view the current glyph view

  • applicationDidFinishLaunching
    Send when RoboFont did finish launching.
  • applicationDidBecomeActive
    Send when RoboFont become the active application.
  • applicationWillResignActive
    Send when RoboFont resigns being the active application.
  • binaryFontWillOpen
    Send when a binary font will open.
    font  the font object
    source the fontTools source object
    format the format of the source font
  • fontBecameCurrent
    font  the font object
  • fontResignCurrent
    font  the font object
  • fontWillSave
    Send when a font will save.
    font the font object
    path the path where the font will be saved
  • fontDidSave
    Send when a font is done saving.
    font the font object
    path the path where the font did save
  • fontWillClose
    Send when a font will close.
    font the font object
  • newFontWillOpen
    Send when a new font will open.
    font the font object
  • newFontDidOpen
    Send when a new font did open.
    font the font object
  • fontWillOpen
    Send when a font will open.
    font the font object
  • fontDidOpen
    Send when a font did open.
    font the font object
  • fontWillAutoSave
    Send when a font will auto save.
    font the font object
    path the path where the font did autosave
  • fontDidAutoSave
    Send when a font did auto save.
    font the font object
    path the path where the font did autosave
  • fontDidChangeExternally
    Send when a font did change externally, outside RoboFont.
    font the font object
  • fontWillGenerate
    Send when a font will generate.
    font the font object
    format the format of the generated font
    path the path where the binary font will save
  • fontDidGenerate
    Send when a font did generate.
    font the font object
    format the format of the generated font
    path the path where the binary font will save
  • currentGlyphChanged
    Send when the current glyph changed, this can be either in the glyph view or in the font overview.
  • viewWillChangeGlyph
    Send when the glyph view will switch to an other glyph.
  • viewDidChangeGlyph
    Send when the glyph view did switch to an other glyph.
  • glyphWindowWillOpen
    Send when a glyph window will open.
    window the glyph window that will open
  • glyphWindowDidOpen
    Send when a glyph window did open.
    window the glyph window that did open
  • glyphWindowWillClose
    Send when a glyph window will close.
    window the glyph window that will close
  • spaceCenterWillOpen
    Send when a space center will open.
    window the space center window that will open
  • spaceCenterDidOpen
    Send when a space center did open.
    window the space center window that did open
  • spaceCenterWillClose
    Send when a space center will close.
    window the space center window that will close
  • transformChanged
    Send when a transformation is applied to a glyph.
    scale
    translate
    rotate
    skew
    repeatMatrix
  • extensionDidGenerate
    Send when an extension did generate.
    path the path to the extension
  • spaceCenterDraw
    Send when a space center draws a glyph, this can happen a lot so be care full.
    scale the drawing scale
    spaceCenter the space center
    selected a bool if the glyph is selected in the space center
  • spaceCenterKeyDown
    Send on a key down in a space center.
    event the NSEvent object
    spaceCenter the space center
  • spaceCenterKeyUp
    Send on a key up in space center.
    event the NSEvent object
    spaceCenter the space center
  • drawPreview
    Send when the glyph view draws a preview.
    scale
  • drawBackground
    Send when the glyph view draws the background, before the actual glyph data.
    scale
  • draw
    Send when the glyph view draw the glyph data.
    scale
  • drawInactive
    Send when the glyph view draw when the glyph window is not the active one.
    scale
  • mouseDown
    Send on mouse down in the glyph view.
    point the point coordinates of the mouse in the glyph coordinate system
    clickCount the click count
    offset offset of the zero zero point in the glyph view
    event the NSEvent object
  • rightMouseDown
    Send on right mouse down in the glyph view.
    point the point coordinates of the mouse in the glyph coordinate system
    event the NSEvent object
  • mouseDragged
    Send on a mouse drag in the glyph view.
    point the point coordinates of the mouse in the glyph coordinate system
    offset offset of the zero zero point in the glyph view
    delta delta of the drag form the first click
    event the NSEvent object
  • rightMouseDragged
    Send on a right mouse drag in the glyph view.
    point the point coordinates of the mouse in the glyph coordinate system
    offset offset of the zero zero point in the glyph view
    event the NSEvent object
  • mouseUp
    Send on a mouse up in the glyph view.
    point the point coordinates of the mouse in the glyph coordinate system
    offset offset of the zero zero point in the glyph view
    event the NSEvent object
  • keyDown
    Send on a key down in the glyph view.
    event the NSEvent object
  • keyUp
    Send on a key up in the glyph view.
    event the NSEvent object
  • modifiersChanged
    Send when the modifier changed in the glyph view (command, alt, control and shift keys)
    event the NSEvent object
  • toggleTransformMode
    Send when the glyph view toggles from or out the transform mode.
  • acceptMenuEditCallbacks
    Send when a contextual menu is been build.
    item a menu item
  • selectAll
    Send on select all in the glyph view.
  • deselectAll
    Send on deselect all in the glyph view.
  • selectAllAlternate
    Send on select all alternate in the glyph view.
  • copy
    Send on copy in the glyph view.
  • copyAsComponent
    Send on copy as component in the glyph view.
  • cut
    Send on cut in the glyph view.
  • delete
    Send on delete in the glyph view.
  • paste
    Send on paste in the glyph view.

Custom Tools

You can add custom tools to RoboFont, by subclassing the BaseEventTool class or an existing core tool. RoboFont core tools are BezierDrawingTool, EditingTool, MeasurementTool and SliceTool. They are available through the mojo.events module.

from mojo.events import BaseEventTool 
## or subclassing a core tool
from mojo.events import BezierDrawingTool, EditingTool, MeasurementTool, SliceTool

This is an easy example, with most event callback. You need the installTool to tell RoboFont you want to install in a new tool.
Custom tools can also be activated at start up through the preferences.

example:

from mojo.events import BaseEventTool, installTool
from AppKit import *

class MyEvent(BaseEventTool):

    def becomeActive(self):
        print "active"

    def becomeInactive(self):
        print "inactive"

    def mouseDown(self, point, clickCount):
        # getGLyph returns the current glyph as robofab object
        print "mouseDown", self.getGlyph(), clickCount

    def rightMouseDown(self, point, event):
        print "rightMouseDown"

    def mouseDragged(self, point, delta):
        print "mousedragged"

    def rightMouseDragged(self, point, delta):
        print "rightMouseDragged"

    def mouseUp(self, point):
        print "mouseup"

    def keyDown(self, event):
        # a dict of all modifiers, shift, command, alt, option
        print "keyDown", self.getModifiers() 

    def keyUp(self, event):
        print "keyUp"

    def modifiersChanged(self):
        print "modifiersChanged"

    def draw(self, scale):
        print "draw", self.isDragging()
        if self.isDragging():
            ## draw a red dot when dragging
            r = 50
            NSColor.redColor().set()
            x, y = self.currentPoint
            NSBezierPath.bezierPathWithOvalInRect_(((x-r, y-r), (r*2, r*2))).fill()

    def drawBackground(self, scale):
        print "drawBackground here"

    #def getDefaultCursor(self):
    #   this will be the cursor default is an arrow
    #   return aNSCursor
    #def getToolbarIcon(self):
    #   this is setting the icon in the toolbar default is an arrow
    #   return aNSImage

    def getToolbarTip(self):
        return "My Event Tool Bar Tip"

    #notifications

    def viewDidChangeGlyph(self):
        print "view changed glyph"

    def preferencesChanged(self):
        print "prefs changed"

installTool(MyEvent())

Tools Methods

  • getGlyph()
    Returns the current glyph used by the tool 
  • getNSView()
    Returns the current glyph view 
  • getCurrentEvent()
    Returns the current NSEvent.
  • refreshView()
    updates the current glyph view
  • setCursor(cursor=None)
    Sets the cursor as current cursor (needs a NSCursor object), if None is given it will be return to default cursor of the tool
  • isDraggin()
    Returns a bool if the tool is draggin
  • zoomRect(offset=None)
    zoom to a given rect
  • toggleTransformMode()
    Toggle the transform
  • getDefaultCursor()
    returns the default cursor for the tool, this must be overwritten
  • getToolbarIcon()
    returns the toolbar icon for the tool, this must be overwritten
  • mouseDown(point, clickCount)
    send a mouse down notification to the tool, with the mouse point in the and the clickCount
  • rightMouseDown(point, clickCount)
    send a right mouse down notification to the tool, with the mouse point in the and the clickCount
  • modifyPoint(point)
    modify the point coordinates
    In the embedded tools this is used to modify the point when fe. on shiftDown
  • mouseMoved(point)
    send a mouse moved notification to the tool, be careful and optimize the code cause the mouse moves all the time
  • mouseDragged(point, delta)
    send a mouse dragged notification to the tool, the delta is the difference between the previous drag point
  • rightMouseDragged(point, delta)
    send a right mouse dragged notification to the tool, the delta is the difference between the previous drag point 
  • mouseUp(point)
    send a mouse up notification to the tool
  • isDragging()
    returns a bools if the tool is in a dragging event
  • keyDown(event)
    send a key down notification to the tool, possible to get the pressed characters by event.characters()
  • keyUp(event)
    send a key up notification to the tool 
  • modifiersChanged()
    send a modifiers changed notification to the tool, happens when shift, command, control, alt is changed
  • getModifiers()
    returns a dictionary with all the modifiers keys as bools. True when pressed down, keys are: shiftDowncommandDownoptionDowncontrolDown
  • getArrowsKeys()
    returns a dictionary with all the arrows keys as bools. True when pressed down, keys are: up, down, left, right

Tools Menu methods

  • acceptMenuEditCallbacks()
    Overwrite this if you want your tool to accept menu callbacks.
  • selectAll()
    perform a select all in your tool, don't overwrite it if you don't want to do anything with it
  • selecteAllAlternate()
    perform a select all in your tool with alt key down, don't overwrite it if you don't want to do anything with it
  • deselectAll()
    perform a deselect all in your tool, don't overwrite it if you don't want to do anything with it
  • copy()
  • copyAsComponent()
  • cut()
  • delete()
  • paste()
  • additionContectualMenuItems()
    called when a contextual menu is created, it is required to return a list of tuples with a title string and a callback function
    example [("additional stuff", myObject.myAdditionMenuCallback), ]

Tools Draw Methods

  • draw(scale)
    draw in the glyph
  • drawBackground(scale)
    draw in the background of the glyph view
  • drawPreview(scale)
    additional drawing in the glyph view while holding the glyph view preview key
  • drawInactive(scale, glyph, view)
    additional drawing in the glyph view when the glyph view is not active, the glyph will not be the current glyph, same for the view
  • drawBackgroundSelection(scale)
    draw in the background, should be related to a selection
  • drawSelection(scale, glyph, view)
    draw the selection for a glyph in a view

Space Center

  • spaceCenterDraw(glyph, scale, selected, spaceCenter)
    draw in the space center for given glyph
  • spaceCenterKeyDown(glyph, event, spaceCenter)
    send a key down notification to the tool, possible to get the pressed characters by event.characters()
  • spaceCenterKeyUp(glyph, event, spaceCenter)
    send a key up notification to the tool 

Tools Notifications Methods

  • viewWillChangeGlyph()
    the glyph in the current view will change
  • viewDidChangGlyph()
    the glyph in the current view did change
  • currentGlyphChanged()
    the current glyph in the app changed
  • preferencesChanged()
    the user defaults changed
  • becomeInactive()
    the tool becomes inactive
  • becomeActive()
    the tool becomes active
  • didUndo()
    a undo notification when the undo is already performed
  • glyphWindowWillOpen()
    a new glyph window will open
  • glyphWindowDidOpen()
    a new glyph window did open
  • glyphWindowWillClose()
    a glyph window will close
  • spaceCenterWillOpen()
    a new Space Center will open
  • spaceCenterDidOpen()
    a new Space Center did open
  • spaceCenterWillClose()
    a Space Center will close
  • fontWillOpen(font)
    a UFO will been opened
  • fontDidOpen(font)
    a UFO did open 
  • newFontWillOpen(font)
    a new UFO will been created
  • newFontDidOpen(font)
    a new UFO is been created 
  • binaryFontWillOpen(font, source, format)
    a binary font will open
    the source is the fontTools font object 
  • fontWillClose(font)
    a UFO is been closed
  • applicationDidFinishLauching() 
    the app is ready launching
  • applicationDidBecomeActive()
    the app becomes active
  • applicationWillResignActive()
    the app will resign being active
  • fontBecameCurrent(font)
    a font becomes active
  • fontResignCurrent(font) 
    a font resigns being active 
  • fontWillAutoSave(font)
    font will auto save
  • fontDidAutoSave(font)
    font did auto save
  • fontWillSave(font, path)
    font will save
  • fontDidSave(font, path)
    font did save
  • fontWillGenerate(font, format, path)
    font will generate to a binary format
  • fontDidGenerate(font, format, path) 
    font did generate to a binary format
  • fontDidChangeExternally(font)
    An external change to the font has happend 

Tools Attributes

  • allPointList
    A list of clicked and dragged points used by the tool
  • mouseDownPoints
    A list of clicked points used by the tool
  • shiftDown
    Bool if shift is down 
  • commandDown
    Bool if command is down 
  • optionDown
    Bool if option is down 
  • controlDown
    Bool if control is down 
  • spaceBarDown
    Bool if space is down 
  • arrowKeysDown
    a dictionary of bools with keys: up, down, left, right
  • currentPoint
    returns the last points from the allPointsList
  • selection
    returns the current glyph selection object 

RoboFab extras

See the RoboFab site for an extended object descriptions. There are some additional RoboFont specific methods and attributes added to some objects.

Base Objects

Allmost every class used has some additional attributes.

Methods

  • addObserver(observer, methodName, notification)
    adds an observer to the object that notifies the methodName of the observer for a given notification
  • removeObserver(observer, notification)
    removes the observer for a  given notification

Font Object

Create a new font object:

  • RFont(path=None, showUI=True)
    ShowUI will toggle the creating of all interface objects around a font.

Methods

  • document()
    returns the related NSDocument
  • renameGlyph(oldName, newName, renameComponents=True, renameGroups=True, renameKerning=True)
    Rename a glyph in the font.
    Optionally the glyph can be renamed in all component references, groups and kerning.
  • generate(path, format, decompose=False, checkOutlines=False, autohint=False, releaseMode=False, glyphOrder=None, progressBar=None, useMacRoman=False)
    Generate a font binary to the given path with the given format ("otf", "ttf", "pfa")
    Adding a progressBar object will show you the progress during compiling the font.
  • removeOverlap()
    removes all overlaps in every glyphs
  • extremePoints()
    adds extremes points for every glyph
  • testInstall()
    test instals the font, it returns the ID of the installed font on the os.
  • removeLayer(layerName)
    removes a complete layer, to create a layer just ask any glyph.getLayer("myLayerName")
  • addGuide((x, y), angle, name="")
    adds a guide at point x, y with angle and name
    returning the created guide
  • removeGuide(guide)
    gwill remove the guide from the font
  • update()
    tell the UI that a font has changed directly
  • prepareUndo(undoTitle="")
    This marks to glyph to be ready that a action begins and it should be recorded to create an undo item when its done
  • performUndo()
    creates the undo item
  • setLayerDisplay(layerName, option, value)
    set display options for layers option: Fill, Stroke, Points, Coordinates

Attributes

  • glyphOrder
    returns a list of glyph names in a specific order, it is possible to set the a list with a specific order in a font
  • layerOrder
    returns a list of layernames
  • guides
    a list of all the guides in the glyph
  • templateSelection
    next to the font.selection, which only contains glyphs in the font there is also a selection of template glyphs

Glyph Object

Methods

  • addGuide((x, y), angle, name="")
    adds a guide at point x, y with angle and name
    returning the created guide
  • removeGuide(guide)
    will remove the guide from the glyph
  • addImage(path, offset=None)
    adds an image from path  with offset
    returning the created guide
  • clearImage()
    remove the image
  • removeOverlap()
    removes all overlaps in every glyphs
  • extremePoints()
    adds extremes points for every glyph
  • deselect()
    deselect everything
  • getLayer(layerName, clear=True)
    return the glyph for that layer, create a layer new layer if the layerName doesn't exists
  • copyToLayer(layerName, clear=True)
    copy the current layer to the a layer with the layerName
  • swapToLayer(layerName)
    swap current layer with the a layer with the layerName
  • flipLayers(layer1Name, layer2Name)
    flip layers
  • update()
    tell the UI that the glyph has changed directly

Attributes

  • angledLeftMargin
    returns the angled left margin based on the italic angle in the font.info
  • angledRightMargin
    returns the angled right margin based on the italic angle in the font.info
  • mark
    a tuple of 4 (r, g, b, a)
  • image
    the image object, if no image is set it will be None
  • guides
    a list of all the guides in the glyph
  • selection
    a list of selected points
  • selected
    returning True or False if yhe object is selected or not

 Boolean Glyph

  • glyph | otherGlyph
    returns the union of the contours
  • glyph % otherGlyph
    returns the difference of the glyph contours
  • glyph & otherGlyph
    returns the intersection of the glyph contours
  • glyph ^ otherGlyph
    returns the xor of the glyph contours

Guide Object

Attributes

  • x
    The x of origin the guide.
  • y
    The y of origin the guide.
  • angle
    The angle of guide.
  • name
    The name of the guide
  • isGlobal
    returning if the guide is connected to a font object or glyph object

Image Object

Methods

  • transform(tranformation)
    Transform the image with a transform matrix (xy, yy, xx, yx, x, y)
  • move((x, y))
    Move the image with a given x, y
  • translate((x, y))
    Translate the image with a given x, y
  • skew(angle, offset=None)
    Skew the image with a given angle, optionally with an offset (x, y)
  • rotate(angle, offset=None)
    Rotate the image with a given angle, optionally with an offset (x, y)
  • scale((x, y), center=(0, 0))
    Scale the image with a given x, y, optionally with a center coordinate

Attributes

  • path
    path to the image
  • bounds
    image bounding box
  • brightness
    set brightness of the image (float)
  • contrast
    set contrast of the image (float)
  • saturation
    set saturation of the image (float)
  • sharpness
    set sharpness of the image (float)
  • blackAndWhite
    convert image to black and white (bool)
  • selected

Contour Object

Methods

  • join()
    will close an open contour
  • extremePoints()
    adds extremes points for every glyph