def update(self): self.glyph_window = CurrentGlyphWindow() if self.glyph_window is not None: self.glyph = CurrentGlyph() self.font = self.glyph.getParent() self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.font_index = self.all_fonts.index(self.font) self._update_text_box() return True else: f = CurrentFont() if f is not None: self.font = f self.font_index = self.all_fonts.index(self.font) glyph_names = get_glyphs(f) if len(glyph_names) > 0: self.glyph = self.font[glyph_names[0]] self.glyph_index = self.font.glyphOrder.index( self.glyph.name) self.glyph_window = OpenGlyphWindow(self.glyph, newWindow=False) self._update_text_box() return True else: print(no_glyph_selected) return False else: print(no_font_open) return False
def up_left_callback(self, sender): self.get_nudge() if self.interpolated: nudgeSelected((-self.nudge, self.nudge)) else: shift_selected_points_x(CurrentGlyph(), -self.nudge) shift_selected_points_y(CurrentGlyph(), self.nudge)
def clearButtonCallback(self, sender): myGlyph = CurrentGlyph() for eachContour in myGlyph: for eachPt in eachContour.points: if eachPt.name is not None: eachPt.name = None myGlyph.update()
def italicizeCallback(self, sender=None): italicAngle = self.getItalicAngle() italicSlantOffset = self.getItalicSlantOffset() if self.w.fontSelection.get() == 0: if CurrentFont() is not None: fonts = [CurrentFont()] else: fonts = [] else: fonts = AllFonts() if self.w.glyphSelection.get() == 0 and CurrentGlyph() is not None: glyphs = [CurrentGlyph()] elif self.w.glyphSelection.get() == 1: glyphs = [] for f in fonts: for gname in CurrentFont().selection: if gname in f: glyphs.append(f[gname]) else: glyphs = [] for f in fonts: for g in f: glyphs.append(g.name) for glyph in glyphs: italicize(glyph, italicAngle, offset=italicSlantOffset, shouldMakeReferenceLayer=self.w.makeReferenceLayer.get())
def _roundCurrentGlyph(self): if self.sourceLayerName == self.targetLayerName: self.showMessage( 'ERROR', u'source layer name and target layer name should be different') return None currentGlyph = CurrentGlyph() if currentGlyph is not None: self.rounderLogger.info( 'start: _roundCurrentGlyph(), glyph {} from {} {}'.format( currentGlyph.name, self.selectedFont.info.familyName, self.selectedFont.info.styleName)) selectedFont = currentGlyph.getParent() roundingsData = pullRoundingsDataFromFont(selectedFont) if roundingsData is not None: makeGlyphRound(currentGlyph, roundingsData, sourceLayerName=self.sourceLayerName, targetLayerName=self.targetLayerName) UpdateCurrentGlyphView() self.rounderLogger.info( 'end: _roundCurrentGlyph(), glyph {} from {} {}'.format( currentGlyph.name, selectedFont.info.familyName, selectedFont.info.styleName)) elif currentGlyph is not None: self.showMessage('ERROR', NO_DATA_INTO_FONT) self.rounderLogger.error(NO_DATA_INTO_FONT) else: self.showMessage('ERROR', NO_GLYPH_TO_ROUND) self.rounderLogger.error(NO_GLYPH_TO_ROUND)
class StencilPreview(BaseWindowController): def __init__(self): self.glyph = CurrentGlyph() # create a window self.w = FloatingWindow((400, 400), "Stencil Preview", minSize=(200, 200)) # add the preview to the window self.w.preview = GlyphPreview((0, 0, -0, -0)) # add an observer to get callbacks when a glyph changes in the glyph view addObserver(self, "viewDidChangeGlyph", "viewDidChangeGlyph") # open the window self.updateGlyph() self.w.open() def viewDidChangeGlyph(self, notification): # notification when the glyph changes in the glyph view glyph = CurrentGlyph() self.unsubscribeGlyph() self.subscribeGlyph(glyph) self.updateGlyph() def glyphChanged(self, notification): self.updateGlyph() def updateGlyph(self): glyph = self.glyph # if the glyph is None just set None to the preview if glyph is None: self.w.preview.setGlyph(None) return # get the foreground layer foreground = glyph.getLayer("foreground") # get the background layer background = glyph.getLayer("background") # get the substract the background from the foreground layer result = foreground % background # set the result in the preview view self.w.preview.setGlyph(result) def subscribeGlyph(self, glyph): # subscribe the glyph self.glyph = glyph # add an observer to glyph data changes self.glyph.addObserver(self, "glyphChanged", "Glyph.Changed") def unsubscribeGlyph(self): # unsubscribe the glyph if self.glyph is None: return # remove this observer for the glyph self.glyph.removeObserver(self, "Glyph.Changed") def windowCloseCallback(self, sender): # notification when the window get closed # remove the view did change glyph in the glyph view observer removeObserver(self, "viewDidChangeGlyph") # unsubscribe the glyph self.unsubscribeGlyph() super(StencilPreview, self).windowCloseCallback(sender)
def view_callback(self, sender): if sender.get(): self.on() else: self.off() # update glyph view g = CurrentGlyph() g.changed()
def clearLibCallback(self, sender): if PLUGIN_KEY in CurrentGlyph().lib: del CurrentGlyph().lib[PLUGIN_KEY] if version[0] == '2': CurrentGlyph().changed() else: CurrentGlyph().update() UpdateCurrentGlyphView()
def view_callback(self, sender): if sender.get(): self.on() else: self.off() # update glyph view g = CurrentGlyph() g.update()
def attachLabelToSelectedPoints(labelName): myGlyph = CurrentGlyph() for eachContour in myGlyph: for eachPt in eachContour.points: if eachPt.selected is True: eachPt.name = labelName myGlyph.update() UpdateCurrentGlyphView()
def updateGlyph(self): if CurrentGlyph(): self.glyph = CurrentGlyph() self.leftMargin = self.glyph.leftMargin if self.status == 1: removeObserver(self, "draw") self.updateGlyphView() if self.status == 0: addObserver(self, "drawText", "draw") self.updateGlyphView()
def convertCurrentGlyphCallback(self, sender): g = CurrentGlyph() if None == g: return layerToConvert = self.layers[self.w.layerPopup.get()] if layerToConvert == 'foreground': Message("I can only convert contours from a layer different from 'foreground'.") return g.flipLayers('foreground', layerToConvert) g.copyToLayer(layerToConvert) convert(g, self.maxDistanceValue, self.minLengthValue, self.useArcLength) CurrentFont().changed() UpdateCurrentGlyphView()
def _saveImage(self, path, multipage): # extract glyph name and layername for the path # full syntax: 'a(background).glyph' # draw in glyph with name 'a' in the 'background' layer glyphName, ext = os.path.splitext(os.path.basename(path)) # extract the layername layerName = layerNameRE.findall(glyphName) # replace the layername by nothing glyphName = layerNameRE.sub("", glyphName) # layer name found if layerName: layerName = layerName[0] else: layerName = None # if there is an extension --> there is a glyph name # get the glyph from the CurrentFont # otherwise draw in the CurrentGlyph if ext: font = CurrentFont() if glyphName not in font: dest = font.newGlyph(glyphName) if dest is None: raise GlyphDrawBotError("No font available to draw in") dest.width = 500 else: dest = font[glyphName] else: dest = CurrentGlyph() # can not found a proper glyph to draw in if dest is None: raise GlyphDrawBotError("No glyph available to draw in") dest.clear() multiplePages = len(self._glyphs) > 1 for count, glyph in enumerate(self._glyphs): if layerName: if multiplePages: n = "%s_%s" % (layerName, count + 1) else: n = layerName destLayer = dest.getLayer(n) else: destLayer = dest layerName = "drawBot" destLayer.appendGlyph(glyph) if glyph.image: image = glyph.image destImage = destLayer.addImage(image.data) destImage.transformation = image.transformation destImage.brightness = image.brightness
def _distributeSpacing(self, index, title): glyph = CurrentGlyph() if glyph is None: return rects, selectedContours, selectedBPoints = getSelectionData(glyph) if len(rects) < 3: return widths = [] heights = [] edgeRect = None for rect in rects: xMin, yMin, xMax, yMax = rect widths.append(xMax - xMin) heights.append(yMax - yMin) if edgeRect is None: edgeRect = rect else: edgeRect = unionRect(edgeRect, rect) objectWidth = sum(widths) objectHeight = sum(heights) xMin, yMin, xMax, yMax = edgeRect overallWidth = xMax - xMin overallHeight = yMax - yMin availableXSpace = overallWidth - objectWidth availableYSpace = overallHeight - objectHeight xSpace = availableXSpace / (len(rects) - 1) ySpace = availableYSpace / (len(rects) - 1) spaceBetweenObjects = (xSpace, ySpace)[index] ordered = [(bPoint.anchor[index], (bPoint.anchor[0], bPoint.anchor[1], bPoint.anchor[0], bPoint.anchor[1]), bPoint) for bPoint in selectedBPoints] ordered += [(contour.bounds[index], contour.bounds, contour) for contour in selectedContours] ordered.sort() glyph.prepareUndo(title) prevEdge = None for pos, bounds, obj in ordered[:-1]: xMin, yMin, xMax, yMax = bounds width = xMax - xMin height = yMax - yMin size = (width, height)[index] if prevEdge is None: newPos = (xMin, yMin)[index] else: newPos = prevEdge + spaceBetweenObjects d = newPos - pos print(d) if d != 0: if index == 0: obj.moveBy((d, 0)) else: obj.moveBy((0, d)) prevEdge = newPos + size for bPoint in selectedBPoints: bPoint.round() for contour in selectedContours: contour.round() glyph.changed() glyph.performUndo() UpdateCurrentGlyphView()
def setIndiValues(self, sender): self.roundValues() g = CurrentGlyph() if 'morf' not in g.lib.keys(): g.lib['morf'] = {} g.lib['morf'][self.currentRecipe] = {} l = g.lib['morf'][self.currentRecipe] l['widthBy'] = self.width l['heightBy'] = self.height l['weightByX'] = self.weightx l['weightByY'] = self.weighty l['factor'] = self.factor
def loadGlyph(self): self._inGlyphLoad = True self.glyph = CurrentGlyph() if self.glyph.bounds is None: self.setFirstResponder(self.w.widthField) else: self.setFirstResponder(self.w.leftField) leftField = self.w.leftField.getNSTextField() rightField = self.w.rightField.getNSTextField() leftField.setNextKeyView_(rightField) rightField.setNextKeyView_(leftField) self._updateFields() self._updateButtons() self._inGlyphLoad = False
def apply_callback(self, sender): # get current glyph self.glyph = CurrentGlyph() # no glyph window open if self.glyph is None: print(no_glyph_open) else: # collect points self.points = [] for c in self.glyph: print(c.selection) for p in c.points: if p.selected: self.points.append(p) self.x_pos_list.append(p.x) self.y_pos_list.append(p.y) # not enough points selected if len(self.points) < 2: print(at_least_two_points) else: self._get_parameters() self.glyph.prepareUndo('align points') # select axis if self.axis == 0: values_list = self.x_pos_list else: values_list = self.y_pos_list # get aligment point if self.mode == 1: pos = get_med(values_list) elif self.mode == 2: pos = get_max(values_list) else: pos = get_min(values_list) # align points for p in self.points: # get delta if self.axis == 0: delta_x = pos - p.x delta_y = 0 else: delta_x = 0 delta_y = pos - p.y # move points p.move((delta_x, delta_y)) # done self.glyph.update() self.glyph.performUndo()
def copySpacingCallback(self, sender): '''Copy margin from current glyph to other glyphs in left/right spacing class.''' glyph = CurrentGlyph() if not glyph: return if glyph.bounds is None: return if glyph.font is None: return siblings = getSiblings(glyph, self.side) if not siblings: return beam = self.beam if self.useBeam else None copyMargins(glyph, siblings, self.side, beam=beam, allLayers=self.allLayers, verbose=self.verbose)
def setSpaceCenterWindowPosSize(font, targetLayer=None): w = CurrentSpaceCenterWindow() print("2 CurrentSpaceCenterWindow", id(CurrentSpaceCenterWindow)) g = CurrentGlyph() if g is not None: currentGlyphName = g.name else: currentGlyphName = None posSize = w.window().getPosSize() c = w.getSpaceCenter() rawText = c.getRaw() prefix = c.getPre() suffix = c.getAfter() gnameSuffix = c.getSuffix() size = c.getPointSize() if targetLayer is None: targetLayer = c.getLayerName() # until spaceCenter.setFont works: w = OpenSpaceCenter(font, newWindow=False) new = CurrentSpaceCenterWindow() new.window().setPosSize(posSize) w.setRaw(rawText) w.setPre(prefix) w.setAfter(suffix) w.setSuffix(gnameSuffix) w.setPointSize(size) if targetLayer is not None: w.setLayerName(targetLayer)
def drawDuplicateContours(self, contours, scale): glyph = CurrentGlyph() font = glyph.getParent() duplicateContourColor.set() for contourIndex in contours: contour = glyph[contourIndex] pen = CocoaPen(font) contour.draw(pen) path = pen.path path.fill() path.setLineWidth_(5 * scale) path.stroke() xMin, yMin, xMax, yMax = contour.box mid = calcMid((xMin, yMin), (xMax, yMin)) x, y = mid drawString((x, y - (10 * scale)), "Duplicate Contour", 10, scale, duplicateContourColor)
def update(self): self.glyph_window = CurrentGlyphWindow() if self.glyph_window is not None: self.glyph = CurrentGlyph() self.font = self.glyph.getParent() self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.font_index = self.all_fonts.index(self.font) self._update_text_box() return True else: f = CurrentFont() if f is not None: self.font = f self.font_index = self.all_fonts.index(self.font) glyph_names = get_glyphs(f) if len(glyph_names) > 0: self.glyph = self.font[glyph_names[0]] self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.glyph_window = OpenGlyphWindow(self.glyph, newWindow=False) self._update_text_box() return True else: print no_glyph_selected return False else: print no_font_open return False
def addMissingAnchors(self, sender): g = glyph = CurrentGlyph() glyphName = g.name if ".sc" in glyphName: glyphName = glyphName[:-3] glyphAnchors = list() for anchor in glyph.anchors: glyphAnchors.append(anchor.name) missing = list( set(self.baseDict[glyphName]['anchors']).difference( set(glyphAnchors))) l = g.layerName if "FullHeight" in l: height = CurrentFont().info.capHeight elif ".sc" in g.name: height = CurrentFont().info.xHeight elif g.name[0] == g.name[0].upper(): height = CurrentFont().info.capHeight else: height = CurrentFont().info.xHeight for a in missing: if a == 'top': g.appendAnchor("top", (g.width / 2, height)) elif a == 'bottom': g.appendAnchor("bottom", (g.width / 2, -20)) elif a == 'ogonek': g.appendAnchor("ogonek", (4 * (g.width / 5), 0)) elif a == 'cedilla': g.appendAnchor("cedilla", (g.width / 2, 0)) else: g.appendAnchor(a, (20, height))
def get_glyphs(font): # current_glyph=True, font_selection=True, """ Return current glyph selection in the font as glyph names or ``RGlyph`` objects. """ # get glyphs current_glyph = CurrentGlyph() font_selection = font.selection # get RoboFont's window mode single_window = [False, True][getDefault("singleWindowMode")] # handle multi-window mode glyphs = [] if not single_window: if current_glyph is not None: glyphs += [current_glyph.name] else: glyphs += font_selection # multi-window: return else: if current_glyph is not None: glyphs += [current_glyph.name] glyphs += font_selection else: glyphs += font_selection # done return list(set(glyphs))
def compileGlyphs(self, sender): """ need to rewrite for RF3 """ font = CurrentFont() g = CurrentGlyph() base = g.name l = self.w.list.get() for i in l: if i['checkBox']: accent = i['construction']['accent'] anchor = i['construction']['anchor'] compo = "testcompo" # self.sd[base][accent][anchor] if base not in font.keys(): continue if accent not in font.keys(): continue inBase, height = anchorInGlyph(anchor, font[base]) if inBase and height > 600: if accent + ".cap" in font.keys(): accent = accent + ".cap" inAccent, height = anchorInGlyph(anchor, font[accent]) construction = "%s = %s + %s@%s" % (compo, base, accent, anchor) if not inBase: continue if not inAccent: continue self.compileGlyph(construction)
def checkOnUnicode(self, sender): if sender == self.w.latin_supp: myset = Latin_Supp_block if sender == self.w.latin_A: myset = Latin_Ext_A_block if sender == self.w.latin_B: myset = Latin_Ext_B_block if sender == self.w.latin_add: myset = Latin_Ext_A_block myset = Latin_Ext_additional_block g = CurrentGlyph() defaults = getExtensionDefault(defaultKey, dict()) # print Latin_Supp_block # print # print defaults # print for glyphName in myset: if glyphName == g.name: # g.name for anchorName in myset[glyphName]: # top for accent in myset[glyphName][anchorName]: # grave for listItem in self.w.list.get(): for pijl in pijlen.items(): if listItem["anchor"] == pijl[1]: anchor = pijl[0] if anchor == anchorName and accent == listItem[ 'accent']: listItem['checkBox'] = True
def _updateCurrentFont(self, infoDict): if infoDict['font']: self.currentGlyph = CurrentGlyph() self.distancesController.setCurrentGlyph(self.currentGlyph) # update neighbors self.neighborsController.lftController.updateCurrentGlyph() self.neighborsController.cntController.updateCurrentGlyph() self.neighborsController.rgtController.updateCurrentGlyph()
def operationCallback(self, sender): value = sender.get() roundCoordinates = self.w.roundCoordinates.get() backToFront = self.w.reverseContourOrder.get() if roundCoordinates is None: roundCoordinates = 0 robofabGlyph = CurrentGlyph() if robofabGlyph is None: return glyph = robofabGlyph.naked() selectedContours = glyph.selection.getAllSelectedContours() if not selectedContours: return if backToFront: selectedContours.reverse() subjectContours = selectedContours[:1] clipContours = selectedContours[1:] glyph.prepareUndo("Path Operations") if value == 0: # union removeOverlap(glyph, selectedContours, roundCoordinates) elif value == 1: # difference difference(glyph, subjectContours, clipContours, roundCoordinates) elif value == 2: # intersection intersection(glyph, subjectContours, clipContours, roundCoordinates) elif value == 3: # Xor xor(glyph, subjectContours, clipContours, roundCoordinates) glyph.performUndo() glyph.selection.resetSelection()
def glyphChanged(self, notification): glyph = self.glyph if CurrentGlyph(): glyph = CurrentGlyph() self.glyph = glyph if glyph is not None: if self.status == 0: glyph.leftMargin = self.leftMargin glyph.rightMargin = self.rightMargin # Sends the glyph margins when tool isn’t active # so when you activate it the good margins will be used if self.status == 1: self.leftMargin = glyph.leftMargin self.rightMargin = glyph.rightMargin
def draw(self, info): if not self.calculatePreview: return cur = CurrentGlyph() if cur == None: return scale = info['scale'] layerToConvert = self.layers[self.w.layerPopup.get()] otherLayer = layerToConvert != 'foreground' if (not otherLayer) and ( CurrentFont().lib['com.typemytype.robofont.segmentType'] == 'qcurve'): return if otherLayer: cur.flipLayers('foreground', layerToConvert) copy = cur.copy() if otherLayer: cur.flipLayers('foreground', layerToConvert) convert(copy, self.maxDistanceValue, self.minLengthValue, self.useArcLength) for c in copy: for p in c.points: if p.type == 'offCurve': color = OffColor r = 4 * scale else: color = OnColor r = 6 * scale self.drawDiscAtPoint(r, p.x, p.y, color) save() stroke(0.2, .8, .8, 1) fill(None) strokeWidth(scale) drawGlyph(copy) restore()
def _currentGlyphChangedObserver(self, info=None): self.glyph = CurrentGlyph() if self.font != CurrentFont(): self._saveSettingsToFont() del self.settings self.font = CurrentFont() self._noFontCallback() self._loadSettingsFromFont() UpdateCurrentGlyphView()
def buildAccentList(self, sender=None): self.w = getExtensionDefault(settingsWindow) if not self.w: return font = CurrentFont() glyph = CurrentGlyph() if glyph is None: self.w.setTitle("---") self.w.list.set([]) return glyphName = glyph.name self.w.setTitle(glyphName) if "." in glyphName: glyphName = glyphName.split(".")[0] theAccentsList = [] # defaults = getExtensionDefault(defaultKey+".check", dict()) if glyphName in self.baseDict: for accent in self.baseDict[glyphName]['accents']: for c in self.baseDict[glyphName]['constructions']: # print(c) if c['accent'] == accent: position = c['anchor'] thisConstructon = c if position not in pijlen.keys(): pijlen[position] = position theAccentsList.append( dict( anchor=pijlen[position], accent=accent, checkBox=getExtensionDefault( defaultKey + "." + accent + "@" + position, True), construction=thisConstructon, ), ) if glyphName in self.accentDict: for base in self.accentDict[glyphName]['bases']: for c in self.accentDict[glyphName]['constructions']: # print(c) if c['base'] == base: position = c['anchor'] # key = defaultKey+"."+item["accent"]+"@"+anchor theAccentsList.append( dict( anchor=pijlen[position], accent=base, checkBox=getExtensionDefault( defaultKey + "." + base + "@" + position, True), construction=self.accentDict[glyphName], ), ) self.w.list.set(theAccentsList) # print len(items) self.w.resize(160, 17 + 17 + 17 + 17 + (19 * len(theAccentsList)) + 21)
def updateStatus(self, info): glyph = CurrentGlyph() if glyph is None: font = CurrentFont() if font is None: message = "Im just looking around" else: m = self.parseFontInfo(font) message = "Im working on my %s in RoboFont" % m else: font = glyph.getParent() m = self.parseFontInfo(font) message = "Im drawing glyph %s for %s in RoboFont" % (glyph.name, m) cmd = NSAppleScript.alloc().initWithSource_(appleScript % message) cmd.executeAndReturnError_(None)
def nudgeSelected(x): g = CurrentGlyph() for c in g.contours: i = 0 for p in c.bPoints: n = c.bPoints[i] if n.selected: g.prepareUndo(undoTitle='InterpolatedNudge') interpolateNode(i, g, c, x) g.performUndo() g.update() i = i + 1
def addOverlap(self, sender): g = CurrentGlyph() selection = [] selectedPoints = g.selectedPoints for p in selectedPoints: p.selected = False selection.append((p.x, p.y)) pen = AddOverlapPointPen(selection) g.drawPoints(pen) with g.undo("Add Overlap"): g.clearContours() pen.drawPoints(g.getPointPen()) g.changed()
def __init__(self): self.glyph = CurrentGlyph() # create a window self.w = FloatingWindow((400, 400), "Stencil Preview", minSize=(200, 200)) # add the preview to the window self.w.preview = GlyphPreview((0, 0, -0, -0)) # add an observer to get callbacks when a glyph changes in the glyph view addObserver(self, "viewDidChangeGlyph", "viewDidChangeGlyph") # open the window self.updateGlyph() self.w.open()
def parametersChanged(self, sender=None): glyph = CurrentGlyph() attrValues = self.getAttributes() if glyph is None: outGlyph = None else: outGlyph = self.getGlyph(glyph, *attrValues) selectedPoints = self.getSelectedPoints(outGlyph) self.w.preview.setGlyph(outGlyph) self.w.preview.setSelection(selectedPoints) self.updateSpaceCenters()
def nudgeSelected(offset): g = CurrentGlyph() for c in g.contours: for i, p in enumerate(c.bPoints): n = c.bPoints[i] if n.selected: g.prepareUndo(undoTitle='InterpolatedNudge') interpolateNode(i, g, c, offset) g.performUndo() g.update()
def draw(self, info): if not self.calculatePreview: return cur = CurrentGlyph() if cur == None: return; scale = info['scale'] layerToConvert = self.layers[self.w.layerPopup.get()] otherLayer = layerToConvert != 'foreground' if (not otherLayer) and (CurrentFont().lib['com.typemytype.robofont.segmentType'] == 'qcurve'): return if otherLayer: cur.flipLayers('foreground', layerToConvert) copy = cur.copy() if otherLayer: cur.flipLayers('foreground', layerToConvert) convert(copy, self.maxDistanceValue, self.minLengthValue, self.useArcLength) for c in copy: for p in c.points: if p.type == 'offCurve': color = OffColor r = 4*scale else: color = OnColor r = 6*scale self.drawDiscAtPoint(r, p.x, p.y, color) save() stroke(0.2, .8, .8, 1) fill(None) strokeWidth(scale) drawGlyph(copy) restore()
def apply_callback(self, sender): # get current glyph self.glyph = CurrentGlyph() # no glyph window open if self.glyph is None: print no_glyph_open else: # collect points self.points = [] for c in self.glyph: print c.selection for p in c.points: if p.selected: self.points.append(p) self.x_pos_list.append(p.x) self.y_pos_list.append(p.y) # not enough points selected if len(self.points) < 2: print at_least_two_points else: self._get_parameters() self.glyph.prepareUndo('align points') # select axis if self.axis == 0: values_list = self.x_pos_list else: values_list = self.y_pos_list # get aligment point if self.mode == 1: pos = get_med(values_list) elif self.mode == 2: pos = get_max(values_list) else: pos = get_min(values_list) # align points for p in self.points: # get delta if self.axis == 0: delta_x = pos - p.x delta_y = 0 else: delta_x = 0 delta_y = pos - p.y # move points p.move((delta_x, delta_y)) # done self.glyph.update() self.glyph.performUndo()
class switchGlyphDialog(object): _title = "switch" _padding_top = 8 _padding = 10 _button_1 = 30 _button_2 = 18 _line_height = 18 _box_height = 23 _width = 320 _height = (_button_1 * 3) + (_padding_top * 2) _move_default = 70 def __init__(self): # get fonts self.all_fonts = AllFonts() if len(self.all_fonts) > 0: self.w = FloatingWindow( (self._width, self._height), self._title) # move buttons p = self._padding b1 = self._button_1 b2 = self._button_2 box = self._box_height x = self._padding y = self._padding_top x1 = x + b1 - 1 x2 = x + (b1 * 2) - 2 # buttons self.w._up = SquareButton( (x1, y, b1, b1), unichr(8673), callback=self._up_callback) self.w._up_right = SquareButton( (x2 + 8, y, b1 - 8, b1 - 8), unichr(8599), callback=self._up_right_callback, sizeStyle='small') y += b1 - 1 self.w._left = SquareButton( (x, y, b1, b1), unichr(8672), callback=self._left_callback) self.w._right = SquareButton( (x2, y, b1, b1), unichr(8674), callback=self._right_callback) y += b1 - 1 self.w._down = SquareButton( (x1, y, b1, b1), unichr(8675), callback=self._down_callback) self.w._down_left = SquareButton( (x, y + 8, b1 - 8, b1 - 8), unichr(8601), callback=self._down_left_callback, sizeStyle='small') # location y = p x3 = x2 + b1 + 16 self.w.box_font = Box( (x3, y, -self._padding, self._box_height)) self.w.box_font.text = TextBox( (5, 0, -self._padding, -0), '', sizeStyle='small') y += self._box_height + self._padding_top self.w.box_glyph = Box( (x3, y, -self._padding, self._box_height)) self.w.box_glyph.text = TextBox( (5, 0, -self._padding, -0), '', sizeStyle='small') y += self._box_height + self._padding_top self.w.box_layer = Box( (x3, y, -self._padding, self._box_height)) self.w.box_layer.text = TextBox( (5, 0, -self._padding, -0), '', sizeStyle='small') # open if self.update(): self.w.open() else: print 'please open at least one font first.\n' # methods def next_glyph(self): next = next_glyph(self.font, self.glyph_index) try: self.glyph_window.setGlyphByName(next) except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.setGlyphByName(next) self.update() def previous_glyph(self): prev = previous_glyph(self.font, self.glyph_index) try: self.glyph_window.setGlyphByName(prev) except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.setGlyphByName(prev) self.update() def layer_down(self): try: self.glyph_window.layerDown() except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.layerDown() self.update() def layer_up(self): try: self.glyph_window.layerUp() except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.layerUp() self.update() def _update_text_box(self): self.w.box_font.text.set('%s [%s]' % (get_full_name(self.font), self.font_index)) self.w.box_glyph.text.set('%s [%s]' % (self.glyph.name, self.glyph_index)) self.w.box_layer.text.set(self.glyph.layerName) def update(self): self.glyph_window = CurrentGlyphWindow() if self.glyph_window is not None: self.glyph = CurrentGlyph() self.font = self.glyph.getParent() self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.font_index = self.all_fonts.index(self.font) self._update_text_box() return True else: f = CurrentFont() if f is not None: self.font = f self.font_index = self.all_fonts.index(self.font) glyph_names = get_glyphs(f) if len(glyph_names) > 0: self.glyph = self.font[glyph_names[0]] self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.glyph_window = OpenGlyphWindow(self.glyph, newWindow=False) self._update_text_box() return True else: print 'please select a glyph first.\n' return False else: print 'please open a font first.\n' return False # callbacks def _left_callback(self, sender): self.previous_glyph() def _right_callback(self, sender): self.next_glyph() def _up_callback(self, sender): self.layer_up() def _down_callback(self, sender): self.layer_down() def _up_right_callback(self, sender): if len(self.all_fonts) > 1: # get next font f = CurrentFont() i = self.all_fonts.index(f) try: next_i = i + 1 next_font = self.all_fonts[next_i] except IndexError: next_i = 0 next_font = self.all_fonts[next_i] # get glyph g_current = CurrentGlyph() if g_current is not None: if next_font.has_key(g_current.name): next_glyph = next_font[g_current.name] else: next_glyph = next_font[next_font.glyphOrder[0]] # switch to glyph window G = OpenGlyphWindow(next_glyph, newWindow=False) # update UI self.update() def _down_left_callback(self, sender): if len(self.all_fonts) > 1: # get next font f = CurrentFont() i = self.all_fonts.index(f) try: prev_i = i - 1 prev_font = self.all_fonts[prev_i] except IndexError: prev_i = -1 prev_font = self.all_fonts[prev_i] # get glyph g_current = CurrentGlyph() if g_current is not None: if prev_font.has_key(g_current.name): prev_glyph = prev_font[g_current.name] else: prev_glyph = prev_font[prev_font.glyphOrder[0]] # switch to glyph window G = OpenGlyphWindow(prev_glyph, newWindow=False) # update UI self.update()
class switchGlyphDialog(hDialog): """A dialog to navigate through glyphs, fonts and layers of all open fonts. .. image:: imgs/glyph/switch.png """ # methods def __init__(self): # get fonts self.get_fonts() if len(self.all_fonts) > 0: self.title = "switch" self.text_height += 3 self.square_button -= 4 self.height = (self.square_button * 3) + (self.padding_y * 2) self.width = 320 self.w = HUDFloatingWindow((self.width, self.height), self.title) # move buttons x = self.padding_x y = self.padding_y x1 = x + (self.square_button * 1) - 1 x2 = x + (self.square_button * 2) - 2 self.w._up = SquareButton( (x1, y, self.square_button, self.square_button), unichr(8673), callback=self._up_callback) self.w._up_right = SquareButton( (x2 + 8, y, self.square_button - 8, self.square_button - 8), unichr(8599), callback=self._up_right_callback, sizeStyle=self.size_style) y += self.square_button - 1 self.w._left = SquareButton( (x, y, self.square_button, self.square_button), unichr(8672), callback=self._left_callback) self.w._right = SquareButton( (x2, y, self.square_button, self.square_button), unichr(8674), callback=self._right_callback) y += self.square_button - 1 self.w._down_left = SquareButton( (x, y + 8, self.square_button - 8, self.square_button - 8), unichr(8601), callback=self._down_left_callback, sizeStyle=self.size_style) self.w._down = SquareButton( (x1, y, self.square_button, self.square_button), unichr(8675), callback=self._down_callback) # location y = self.padding_y x3 = x2 + self.square_button + 16 self.w.box_font = Box( (x3, y, -self.padding_x, self.text_height)) self.w.box_font.text = TextBox( (5, 0, -self.padding_x, -0), '', sizeStyle=self.size_style) y += self.text_height + self.padding_y self.w.box_glyph = Box( (x3, y, -self.padding_x, self.text_height)) self.w.box_glyph.text = TextBox( (5, 0, -self.padding_x, -0), '', sizeStyle=self.size_style) y += self.text_height + self.padding_y self.w.box_layer = Box( (x3, y, -self.padding_x, self.text_height)) self.w.box_layer.text = TextBox( (5, 0, -self.padding_x, -0), '', sizeStyle=self.size_style) # open if self.update(): # bind # self.w.bind("became key", self.update_callback) self.w.bind("close", self.on_close_window) # observers addObserver(self, "update_callback", "newFontDidOpen") addObserver(self, "update_callback", "fontDidOpen") addObserver(self, "update_callback", "fontDidClose") # open window self.w.open() else: print no_font_open # methods def get_fonts(self): self.all_fonts = AllFonts() def next_glyph(self): next = next_glyph(self.font, self.glyph_index) try: self.glyph_window.setGlyphByName(next) except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.setGlyphByName(next) self.update() def previous_glyph(self): prev = previous_glyph(self.font, self.glyph_index) try: self.glyph_window.setGlyphByName(prev) except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.setGlyphByName(prev) self.update() def layer_down(self): try: self.glyph_window.layerDown() except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.layerDown() self.update() def layer_up(self): try: self.glyph_window.layerUp() except AttributeError: self.glyph_window = CurrentGlyphWindow() self.glyph_window.layerUp() self.update() def _update_text_box(self): self.w.box_font.text.set(get_full_name(self.font)) self.w.box_glyph.text.set(self.glyph.name) self.w.box_layer.text.set(self.glyph.layerName) def update(self): self.glyph_window = CurrentGlyphWindow() if self.glyph_window is not None: self.glyph = CurrentGlyph() self.font = self.glyph.getParent() self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.font_index = self.all_fonts.index(self.font) self._update_text_box() return True else: f = CurrentFont() if f is not None: self.font = f self.font_index = self.all_fonts.index(self.font) glyph_names = get_glyphs(f) if len(glyph_names) > 0: self.glyph = self.font[glyph_names[0]] self.glyph_index = self.font.glyphOrder.index(self.glyph.name) self.glyph_window = OpenGlyphWindow(self.glyph, newWindow=False) self._update_text_box() return True else: print no_glyph_selected return False else: print no_font_open return False # callbacks def _left_callback(self, sender): self.previous_glyph() def _right_callback(self, sender): self.next_glyph() def _up_callback(self, sender): self.layer_up() def _down_callback(self, sender): self.layer_down() def _up_right_callback(self, sender): if len(self.all_fonts) > 1: # get next font f = CurrentFont() i = self.all_fonts.index(f) try: next_i = i + 1 next_font = self.all_fonts[next_i] except IndexError: next_i = 0 next_font = self.all_fonts[next_i] # get glyph g_current = CurrentGlyph() if g_current is not None: if next_font.has_key(g_current.name): next_glyph = next_font[g_current.name] else: next_glyph = next_font[next_font.glyphOrder[0]] # switch to glyph window G = OpenGlyphWindow(next_glyph, newWindow=False) # update UI self.update() def _down_left_callback(self, sender): if len(self.all_fonts) > 1: # get next font f = CurrentFont() i = self.all_fonts.index(f) try: prev_i = i - 1 prev_font = self.all_fonts[prev_i] except IndexError: prev_i = -1 prev_font = self.all_fonts[prev_i] # get glyph g_current = CurrentGlyph() if g_current is not None: if prev_font.has_key(g_current.name): prev_glyph = prev_font[g_current.name] else: prev_glyph = prev_font[prev_font.glyphOrder[0]] # switch to glyph window G = OpenGlyphWindow(prev_glyph, newWindow=False) # update UI self.update() def update_callback(self, sender): self.get_fonts() self.update() def on_close_window(self, sender): removeObserver(self, "newFontDidOpen") removeObserver(self, "fontDidOpen") removeObserver(self, "fontDidClose")
import tempfile from mojo.roboFont import CurrentGlyph from AppKit import NSPNGFileType, NSBitmapImageRep g = CurrentGlyph() result = g.getRepresentation("money.money.money") if result: im, offset = result imagePath = tempfile.mkstemp(suffix=".png")[1] imageRep = NSBitmapImageRep.imageRepWithData_(im.TIFFRepresentation()) imageData = imageRep.representationUsingType_properties_(NSPNGFileType, None) imageData.writeToFile_atomically_(imagePath, True) g.addImage(path=imagePath, position=offset)
class alignPointsDialog(hConstants): """Align selected points vertically or horizontally.""" glyph = None points = [] x_pos_list = [] y_pos_list = [] axis = 1 mode = 1 def __init__(self): # window parameters self.title = 'align' self.width = 123 self.column1 = 45 self.height = (self.padding_y * 4) + self.button_height + (self.text_height * 2) # window self.w = FloatingWindow( (self.width, self.height), self.title) x = self.padding_x y = self.padding_y # options self.w.align_mode = RadioGroup( (x, y, -self.padding_x, self.text_height), [ '-', 'm', '+' ], isVertical=False, sizeStyle=self.size_style) self.w.align_mode.set(self.mode) y += (self.text_height + self.padding_y) # button x = self.padding_x self.w.align_button = SquareButton( (x, y, -self.padding_x, self.button_height), 'apply', callback=self.apply_callback, sizeStyle=self.size_style) y += (self.button_height + self.padding_y) # axis self.w.axis_label = TextBox( (x, y + 3, self.column1, self.text_height), "axis", sizeStyle=self.size_style) x = self.column1 self.w.axis = RadioGroup( (x, y, -self.padding_x, self.text_height), ["x", "y"], sizeStyle=self.size_style, isVertical=False) self.w.axis.set(self.axis) # open self.w.open() def _get_parameters(self): self.axis = self.w.axis.get() self.mode = self.w.align_mode.get() def apply_callback(self, sender): # get current glyph self.glyph = CurrentGlyph() # no glyph window open if self.glyph is None: print no_glyph_open else: # collect points self.points = [] for c in self.glyph: print c.selection for p in c.points: if p.selected: self.points.append(p) self.x_pos_list.append(p.x) self.y_pos_list.append(p.y) # not enough points selected if len(self.points) < 2: print at_least_two_points else: self._get_parameters() self.glyph.prepareUndo('align points') # select axis if self.axis == 0: values_list = self.x_pos_list else: values_list = self.y_pos_list # get aligment point if self.mode == 1: pos = get_med(values_list) elif self.mode == 2: pos = get_max(values_list) else: pos = get_min(values_list) # align points for p in self.points: # get delta if self.axis == 0: delta_x = pos - p.x delta_y = 0 else: delta_x = 0 delta_y = pos - p.y # move points p.move((delta_x, delta_y)) # done self.glyph.update() self.glyph.performUndo()
h = yMax - yMin center_x = xMin + (w / 2) center_y = yMin + (h / 2) # transform glyph.prepareUndo('mirror') glyph.scale((scale_x, scale_y), center=(center_x, center_y)) glyph.performUndo() glyph.update() def _mirror_glyphs(self, (scale_x, scale_y)): f = CurrentFont() if f is not None: #---------------------- # current glyph window #---------------------- g = CurrentGlyph() if g is not None: print 'reflecting current glyph...\n' print '\t%s' % g.name # mirror all layers if self.layers: for layer_name in f.layerOrder: _g = g.getLayer(layer_name) self._mirror_glyph(_g, (scale_x, scale_y)) # mirror active layer only else: self._mirror_glyph(g, (scale_x, scale_y)) print '\n...done.\n' #----------------- # selected glyphs #-----------------