def sortWordsByWidth(self, wordlist): """Sort output word list by width.""" f = CurrentFont() wordWidths = [] for word in wordlist: unitCount = 0 for char in word: try: glyphWidth = f[char].width except: try: gname = self.glyphNamesForValues[char] glyphWidth = f[gname].width except: glyphWidth = 0 unitCount += glyphWidth # add kerning for i in range(len(word) - 1): pair = list(word[i:i + 2]) unitCount += int(self.findKerning(pair)) wordWidths.append(unitCount) wordWidths_sorted, wordlist_sorted = zip(*sorted( zip(wordWidths, wordlist))) # thanks, stackoverflow return wordlist_sorted
def expandSelection(self, sender): font = CurrentFont() preserveComponents = bool(self.w.preserveComponents.get()) selection = font.selection for glyphName in selection: glyph = font[glyphName] self.expandGlyph(glyph, preserveComponents)
def alignToptoAscenderFunction(paths): font = CurrentFont() mm = minmaxPaths(paths) paths = [ path.applyPlus(TFSPoint(0, font.info.ascender - mm.maxY)) for path in paths ] return paths
def run_exportFLK(self, sender): font = CurrentFont() if font != None: ufopath = getUFOpath(font) if ufopath != None: exportKerningFL(font, ufopath) else: print 'Please, open any .vfb with kerning :)' self.w.close()
def centerBelowAscenderFunction(paths): font = CurrentFont() mm = minmaxPaths(paths) paths = [ path.applyPlus( TFSPoint(0, (font.info.ascender - (mm.maxY - mm.minY)) * 0.5)) for path in paths ] return paths
def fontSelectionCallback(self, sender): font = CurrentFont() if font is None: return self.selectedGlyphs = list(font.selection) self.unselectedGlyphs = list( set(self.allGlyphs) - set(self.selectedGlyphs)) self.unselectedGlyphs.sort() self._updateLists()
def _updateExportFileList(self): if self.w.exportCurrentFontCheckBox.get(): font = CurrentFont() if font is None: self.files = {} else: self.files = {font.path: font} else: self.files = {} for font in AllFonts(): self.files[font.path] = font self._updateFileList()
def draw(self): # canvas draw callback drawing.save() self._drawGrid() drawing.restore() font = CurrentFont() if self.show_fixed and self.system is not None and self.system.fixed_units: # display the fixed widths of the current unitization system self.draw_histogram(font, self.system.upm, (0, 0, 1, 0.5), True, histogram=self.system.fixed_units) # draw the histogram for the current font print "__font:", font print "__font.info:", font.info self.draw_histogram(font, font.info.unitsPerEm, (1, 0, 0, 1), True)
def moveAnchor(distancia, sentido, anchorName): f = CurrentFont() if anchorName != '': for g in f: if g.selected: if len(g.anchors) > 0: setAnchor(g, distancia, sentido, anchorName) else: print 'No hay anchors' f.update() else: print "Debe declarar un nombre de anchor primero."
def loadPrefs(self): """Load the saved preferences into the program.""" self.requiredLetters = [] self.requiredGroups = [[], [], []] self.banRepetitions = False # preset character groups self.groupPresets = [["[lc] Ascenders", ["b", "f", "h", "k", "l"]], ["[lc] Descenders", ["g", "j", "p", "q", "y"]], ["[lc] Ball-and-Stick", ["b", "d", "p", "q"]], ["[lc] Arches", ["n", "m", "h", "u"]], ["[lc] Diagonals", ["v", "w", "x", "y"]]] # define initial values initialDefaults = { "com.ninastoessinger.word-o-mat.wordCount": 20, "com.ninastoessinger.word-o-mat.minLength": 3, "com.ninastoessinger.word-o-mat.maxLength": 15, "com.ninastoessinger.word-o-mat.case": 0, "com.ninastoessinger.word-o-mat.limitToCharset": "True", "com.ninastoessinger.word-o-mat.source": 0, "com.ninastoessinger.word-o-mat.matchMode": "text", "com.ninastoessinger.word-o-mat.matchPattern": "", "com.ninastoessinger.word-o-mat.markColor": "None", } registerExtensionDefaults(initialDefaults) # load prefs into variables/properties prefsToLoad = { "wordCount": "com.ninastoessinger.word-o-mat.wordCount", "minLength": "com.ninastoessinger.word-o-mat.minLength", "maxLength": "com.ninastoessinger.word-o-mat.maxLength", "case": "com.ninastoessinger.word-o-mat.case", "matchMode": "com.ninastoessinger.word-o-mat.matchMode", "matchPattern": "com.ninastoessinger.word-o-mat.matchPattern", "reqMarkColor": "com.ninastoessinger.word-o-mat.markColor", } for variableName, pref in prefsToLoad.iteritems(): setattr(self, variableName, getExtensionDefault(pref)) # restore booleans from strings limitPref = "com.ninastoessinger.word-o-mat.limitToCharset" self.limitToCharset = self.readExtDefaultBoolean( getExtensionDefault(limitPref)) if CurrentFont() else False # parse mark color pref # print "***", self.reqMarkColor if self.reqMarkColor is not "None": if type(self.reqMarkColor) is tuple: self.reqMarkColor = tuple(float(i) for i in self.reqMarkColor) else: self.reqMarkColor = "None"
def get_glyphnames_for_histogram(self): font = CurrentFont() mode = self.w.glyph_selection.get() if mode == 0: #print "Analyze Selection" names = font.selection elif mode == 1: #print "Analyze All Glyphs" names = font.glyphOrder print "__Names:", names else: #print "Analyze Charset" all_glyphs = font.glyphOrder selected_charset_name = self.w.charset_selection.getItems()[self.w.charset_selection.get()] names = [name for name in self.charsets[selected_charset_name] if name in all_glyphs] return names
def checkFont(self, useSelection=False, excludeZeroWidth=True): f = CurrentFont() if f is not None: # initialize things self.w.options.progress.start() time0 = time.time() self.excludeZeroWidth = excludeZeroWidth self.f = f glyphNames = f.selection if useSelection else f.keys() glyphList = [f[x] for x in glyphNames] glyphList = self._trimGlyphList(glyphList) self.touchingPairs = Touche(f).findTouchingPairs(glyphList) # display output self.w.results.stats.set("%d glyphs checked" % len(glyphList)) self.w.results.result.set("%d touching pairs found" % len(self.touchingPairs)) self.w.results.show(True) outputList = [{"left glyph": g1, "right glyph": g2} for (g1, g2) in self.touchingPairs] outputStringList = [ "/%s/%s " % (g1, g2) for (g1, g2) in self.touchingPairs ] outputStringMetalist = [outputStringList[i:i + 400] for i in range(0, len(outputStringList), 400)] ActiveFont = self.f._font ActiveFont.disableUpdateInterface() for eachList in outputStringMetalist: outputString = "".join(eachList) ActiveFont.newTab(outputString) self.w.outputList.set(outputList) if len(self.touchingPairs) > 0: self.w.outputList.setSelection([0]) ActiveFont.enableUpdateInterface() #self.w.preview.setFont(f) self.w.options.progress.stop() self._resizeWindow(enlarge=True) time1 = time.time() print u'Touché: finished checking %d glyphs in %.2f seconds' % (len(glyphList), time1-time0) else: Message(u'Touché: Can’t find a font to check')
def apply_callback(self, sender): self.font = CurrentFont() if self.font is not None: gNames = getGlyphs(self.font) if len(gNames) > 0: # print info if self._verbose: print 'rounding glyphs to grid...\n' print '\tgrid size: %s' % self._gridsize print '\tpoints: %s' % self._points print '\tanchors: %s' % self._anchors print '\tside-bearings: %s' % self._sidebearings print '\tmark: %s' % self._mark print print '\t', # batch process glyphs for gName in gNames: print gName, if self._points: roundPointsToGrid(self.font[gName], (self._gridsize, self._gridsize)) if self._anchors: roundAnchorsToGrid(self.font[gName], (self._gridsize, self._gridsize)) if self._sidebearings: roundMargins(self.font[gName], self._gridsize, left=True, right=True) if self._mark: self.font[gName].mark = self._mark_color self.font[gName].update() # done print self.font.update() if self._verbose: print '\n...done.\n' # no glyphs selected else: print 'no glyph to process, please select one or more glyphs and try again.\n' # no font open else: print 'please open a font and try again.\n'
def apply_Callback(self, sender): f = CurrentFont() if f is not None: print 'processing selected glyphs...\n' # get options boolstring = [False, True] _points = self.w._points_checkBox.get() _sidebearings = self.w._sidebearings_checkBox.get() _anchors = self.w._anchors_checkBox.get() # get color _gridsize = int(self.w._gridsize_value.get()) _mark = self.w._mark_checkBox.get() _mark_color = self.w._mark_color.get() _mark_color = (_mark_color.redComponent(), _mark_color.greenComponent(), _mark_color.blueComponent(), _mark_color.alphaComponent()) print '\tgrid size: %s' % _gridsize print '\talign points to grid: %s' % boolstring[_points] print '\talign side-bearings: %s' % boolstring[_sidebearings] print '\talign anchors: %s' % boolstring[_anchors] print '\tmark glyphs: %s (%s)' % (boolstring[_mark], _mark_color) print print '\t', # batch do stuff for gName in f.selection: print gName, f[gName].prepareUndo('align to grid') if _points: roundPointsToGrid(f[gName], (_gridsize, _gridsize)) if _anchors: roundAnchorsToGrid(f[gName], (_gridsize, _gridsize)) if _sidebearings: roundMargins(f[gName], _gridsize, left=True, right=True) if _mark: f[gName].mark = _mark_color f[gName].update() f[gName].performUndo() # done print f.update() print '\n...done.\n'
def calculate_histogram(self, sender=None): print "calculate_histogram" try: font = CurrentFont() #names = self.get_glyphnames_for_histogram() histogram = {} max_width = 0 for name in self.glyphs: width = font[name].width if width > max_width: max_width = width if width in histogram: histogram[width].append(name) else: histogram[width] = [name] self.max_width = max_width self.histogram = histogram except Exception, err: print "calculate_histogram Error" print traceback.format_exc()
def run(): f = CurrentFont() if f != None: myPath = os.path.dirname(f.path) fdkPath = setDirectory(myPath, 'fdk') exportFDKFiles(f, fdkPath) myFile = f.path f.naked().modified = 0 f.close(False) OpenFont(myFile) # revert font else: myPath = GetFolder('Select folder with vfb source files') if myPath: fdkPath = setDirectory(myPath, 'fdk') allFiles = getFilePaths(myPath, '.vfb') for myFile in allFiles: f = OpenFont(myFile) print '' print 'Processing %s...' % os.path.basename(f.path) exportFDKFiles(f, fdkPath) f.naked().modified = 0 f.close(False)
def checkFont(self, useSelection=False, excludeZeroWidth=True): f = CurrentFont() if f is not None: # initialize things self.w.options.progress.start() time0 = time.time() self.excludeZeroWidth = excludeZeroWidth self.f = f glyphNames = f.selection if useSelection else f.keys() glyphList = [f[x] for x in glyphNames] glyphList = self._trimGlyphList(glyphList) self.touchingPairs = Touche(f).findTouchingPairs(glyphList) # display output self.w.results.stats.set("%d glyphs checked" % len(glyphList)) self.w.results.result.set("%d touching pairs found" % len(self.touchingPairs)) self.w.results.show(True) outputList = [{ "left glyph": g1, "right glyph": g2 } for (g1, g2) in self.touchingPairs] self.w.outputList.set(outputList) if len(self.touchingPairs) > 0: self.w.outputList.setSelection([0]) #self.w.preview.setFont(f) self.w.options.progress.stop() self._resizeWindow(enlarge=True) time1 = time.time() print('Touché: finished checking %d glyphs in %.2f seconds' % (len(glyphList), time1 - time0)) else: Message('Touché: Can’t find a font to check')
#FLM: AT Contour order + direction """correctDirection(): correct the direction of all contours in this glyphs. autoContourOrder(): automatically order the contours based on (in this order): the point count of the contours, the segment count of the contours, the x value of the center of the contours, the y value of the center of the contours and the surface of the bounding box of the contours. """ from robofab.world import CurrentFont for g in CurrentFont(): g.autoContourOrder() g.correctDirection()
def cleanupCurrentFontContours(): font = CurrentFont() if font is None: raise Exception('No current font.') cleanupFontContours(font)
def run(writeCoordinates=False): # Get the folder that contains the source hinting data, # and source font files: templateFolderPath = fl.GetPathName( "Select directory that contains the 'tthints' template file...") if not templateFolderPath: 'Cancel was clicked or ESC was pressed' return tthintsFilePath = os.path.join(templateFolderPath, kTTHintsFileName) # Verify that the files tthints, font.pfa/ufo and font.ttf exist # in the folder provided: if not os.path.exists(tthintsFilePath): print "ERROR: Could not find %s file." % kTTHintsFileName return # Check if any of the possible template fonts exists -- PFA, TXT, or UFO: pfaFilePath = os.path.join(templateFolderPath, kPFAFileName) txtFilePath = os.path.join(templateFolderPath, kTXTFileName) ufoFilePath = os.path.join(templateFolderPath, kUFOFileName) if os.path.exists(pfaFilePath): pass elif os.path.exists(txtFilePath): pass elif os.path.exists(ufoFilePath): pass else: print "ERROR: Could not find any of the following font files: %s, %s or %s." % ( kPFAFileName, kTXTFileName, kUFOFileName) return # Check if font.ttf exists in source folder: ttfFilePath = os.path.join(templateFolderPath, kTTFFileName) if not os.path.exists(ttfFilePath): print "ERROR: Could not find %s file." % kTTFFileName return # Get the (root) folder containingt the target font files: baseFolderPath = fl.GetPathName("Select top directory that contains the fonts to process ...") if not baseFolderPath: 'Cancel was clicked or ESC key was pressed' return startTime = time.time() # Create a list of glyphs that have been hinted so it can be # used as a filter. The rawHintingDict contains a string of raw # hinting data for each glyph: glyphList, rawHintingDict = readTTHintsFile(tthintsFilePath) folderPathsList = getFolderPaths(baseFolderPath, templateFolderPath) if len(folderPathsList): delete_temporary_template_PFA = False print "Processing template files..." fl.Open(ttfFilePath) templateTTfont = fl[fl.ifont] if not os.path.exists(pfaFilePath) and os.path.exists(txtFilePath): delete_temporary_template_PFA = True makePFAfromTXT(txtFilePath, pfaFilePath) elif not os.path.exists(pfaFilePath) and os.path.exists(ufoFilePath): delete_temporary_template_PFA = True makePFAfromUFO(ufoFilePath, pfaFilePath, glyphList) fl.Open(pfaFilePath) templateT1font = fl[fl.ifont] # Make a Robofab font of the Type1 template font. This RB font is made # by copying each glyph. There does not seem to be a simpler method # that produces reliable results -- the challenge comes from having # to close the FL font downstream. templateT1RBfont = RFont() currentT1RBfont = CurrentFont() for gName in glyphList: g = currentT1RBfont[gName] templateT1RBfont.insertGlyph(g) hintedNodeDict, indexOnlyRawHintingDict, okToProcessTargetFonts = collectTemplateIndexes( templateTTfont, templateT1font, glyphList, rawHintingDict) closeAllOpenedFonts() if okToProcessTargetFonts: processTargetFonts( folderPathsList, templateT1RBfont, hintedNodeDict, glyphList, indexOnlyRawHintingDict, writeCoordinates) else: print "Can't process target fonts because of hinting errors found in template font." if delete_temporary_template_PFA: if os.path.exists(pfaFilePath): os.remove(pfaFilePath) else: print "Could not find suitable folders to process." endTime = time.time() elapsedSeconds = endTime-startTime if (elapsedSeconds/60) < 1: print '\nCompleted in %.1f seconds.\n' % elapsedSeconds else: print '\nCompleted in %s minutes and %s seconds.\n' % ( elapsedSeconds/60, elapsedSeconds%60)
def processTargetFonts(folderPathsList, templateT1RBfont, hintedNodeDict, glyphList, rawHintingDict, writeCoordinates): totalFolders = len(folderPathsList) print "%d folders found" % totalFolders fontIndex = 1 for targetFolderPath in folderPathsList: deleteTempPFA = False targetFolderName = os.path.basename(targetFolderPath) pfaFilePath = os.path.join(targetFolderPath, kPFAFileName) txtFilePath = os.path.join(targetFolderPath, kTXTFileName) ufoFilePath = os.path.join(targetFolderPath, kUFOFileName) if os.path.exists(pfaFilePath): pass elif os.path.exists(txtFilePath): deleteTempPFA = True makePFAfromTXT(txtFilePath, pfaFilePath) elif os.path.exists(ufoFilePath): deleteTempPFA = True makePFAfromUFO(ufoFilePath, pfaFilePath) else: print "ERROR: Could not find target %s/%s file. Skipping %s folder ..." % ( kPFAFileName, kTXTFileName, targetFolderName) continue ttfFilePath = os.path.join(targetFolderPath, kTTFFileName) if not os.path.exists(ttfFilePath): print "ERROR: Could not find target %s file. Skipping %s folder ..." % ( kTTFFileName, targetFolderName) continue print "\nProcessing %s ... (%d/%d)" % ( targetFolderName, fontIndex, totalFolders) fontIndex += 1 fl.Open(pfaFilePath) targetT1font = fl[fl.ifont] targetT1RBfont = CurrentFont() fl.Open(ttfFilePath) targetTTfont = fl[fl.ifont] newTTHintsFileList = ["# Glyph name\tTT hints\tGlyph color\n"] filteredGlyphList = [ gName for gName in glyphList if gName in hintedNodeDict] for gName in filteredGlyphList: gMark = None gIndex = targetT1font.FindGlyph(gName) if gIndex != -1: glyph = targetT1font[gName] else: print "ERROR: Glyph %s not found in target PS font." % gName continue # Test outline compatibility between the two glyphs # (template and target) templateT1RBglyph = templateT1RBfont[gName] targetT1RBglyph = targetT1RBfont[gName] if not templateT1RBglyph.isCompatible(targetT1RBglyph, False): # NOTE: This method doesn't catch the case in which node # indexes have rotated print "DEFINITELY NOT COMPATIBLE: %s. Skipping..." % gName continue # Verify glyph compatibility by comparing the length of segments: # Create dictionaries of the coodinates of on-curve points: ptDict1 = getGlyphOncurveCoords(templateT1RBglyph) ptDict2 = getGlyphOncurveCoords(targetT1RBglyph) # Define segments using the point coordinates from # ptDict1 and ptDict2: segmentsList = getSegmentsList(ptDict1, ptDict2) if not segmentsList: print "DEFINITELY NOT COMPATIBLE (contour mismatch): %s. Skipping ..." % gName continue # Get all pair combinations of those segments: segmentCombinationsList = list( itertools.combinations(segmentsList, 2)) # Iterate through the segment combinations and stop as soon # as an intersection between two segments is found: for combination in segmentCombinationsList: seg1, seg2 = combination[0], combination[1] if segmentsIntersect(seg1, seg2): print "POSSIBLY NOT COMPATIBLE: %s. Please check ..." % gName gMark = 25 # orange break # one incompatibility was found; # no need to report it more than once # This dictionary is indexed by the combination of the # coordinates of each node of the current glyph: ttGlyphNodeIndexDict = collectTTnodeIndexes(gName, targetTTfont) newHintsList = [] gHintsString = rawHintingDict[gName] gHintsList = gHintsString.split(";") for commandString in gHintsList: commandList = list(eval(commandString)) commandType = commandList[0] if len(commandList): if commandType in deltas: continue elif commandType in alignments: nodes = [commandList[1]] convertedNodes = getNewTTindexes( glyph, nodes, ttGlyphNodeIndexDict, hintedNodeDict) if convertedNodes is not None: writeLine = True targetNodeIndexList, targetNodeCoordsList = convertedNodes hintParamsList = [commandList[-1]] else: writeLine = False break elif commandType in links: nodes = commandList[1:3] convertedNodes = getNewTTindexes( glyph, nodes, ttGlyphNodeIndexDict, hintedNodeDict) if convertedNodes is not None: writeLine = True targetNodeIndexList, targetNodeCoordsList = convertedNodes hintParamsList = commandList[3:] else: writeLine = False break elif commandType in interpolations: nodes = commandList[1:-1] convertedNodes = getNewTTindexes( glyph, nodes, ttGlyphNodeIndexDict, hintedNodeDict) if convertedNodes is not None: writeLine = True targetNodeIndexList, targetNodeCoordsList = convertedNodes hintParamsList = [commandList[-1]] else: writeLine = False break if writeLine: if writeCoordinates: targetNodeList = targetNodeCoordsList else: targetNodeList = targetNodeIndexList newCommandList = [commandType] + targetNodeList + hintParamsList newCommandString = ','.join(map(str, newCommandList)) newHintsList.append(newCommandString.replace(" ", "")) if writeLine: newHintsLine = "%s\t%s" % (gName, ';'.join(newHintsList)) if gMark: newHintsLine = "%s\t%s" % (newHintsLine, gMark) newTTHintsFileList.append(newHintsLine + "\n") saveNewTTHintsFile(targetFolderPath, newTTHintsFileList) closeAllOpenedFonts() if deleteTempPFA: if os.path.exists(pfaFilePath): os.remove(pfaFilePath)
def expandFont(self, sender): font = CurrentFont() preserveComponents = bool(self.w.preserveComponents.get()) for glyph in font: self.expandGlyph(glyph, preserveComponents)
from robofab.world import CurrentFont print CurrentFont()
# robothon06 # use some methods to transform a glyph from robofab.world import CurrentFont font = CurrentFont() # ask a font for a glyph by name glyph = font['A'] # now you have a glyph object # make it do stuff by calling some of its methods glyph.move((100, 75)) glyph.scale((.5, 1.5)) glyph.appendGlyph(font['B']) glyph.removeOverlap() glyph.correctDirection() glyph.update()
def quickModeSelectionCallback(self, sender): mode = self.quickModes[sender.getSelection()] if mode == quickMode_import_selectedFiles_everything: # import self.w.doImportCheckBox.set(True) self.w.saveVFBCheckBox.set(True) self.w.closeVFBCheckBox.set(True) # export self.w.doExportCheckBox.set(False) self.w.exportCurrentFontCheckBox.set(False) self.w.exportAllOpenFontsCheckBox.set(False) self.w.exportFormatVersion1CheckBox.set(False) self.w.exportFormatVersion2CheckBox.set(False) # destination self.w.destinationNewFilesCheckBox.set(True) self.w.destinationExistingFilesCheckBox.set(False) # parts self.w.doFontInfoCheckBox.set(True) self.w.doKerningCheckBox.set(True) self.w.doGroupsCheckBox.set(True) self.w.doLibCheckBox.set(True) self.w.doFeaturesCheckBox.set(True) self.w.doGlyphsText.set("") self.w.doGlyphMarksCheckBox.set(False) self.w.doGlyphMasksCheckBox.set(False) self.w.doGlyphHintsCheckBox.set(False) glyphs = None elif mode == quickMode_export_allFonts_everything: # import self.w.doImportCheckBox.set(False) self.w.saveVFBCheckBox.set(False) self.w.closeVFBCheckBox.set(False) # export self.w.doExportCheckBox.set(True) self.w.exportCurrentFontCheckBox.set(False) self.w.exportAllOpenFontsCheckBox.set(True) self.w.exportFormatVersion1CheckBox.set(False) self.w.exportFormatVersion2CheckBox.set(True) # destination self.w.destinationNewFilesCheckBox.set(True) self.w.destinationExistingFilesCheckBox.set(False) # parts self.w.doFontInfoCheckBox.set(True) self.w.doKerningCheckBox.set(True) self.w.doGroupsCheckBox.set(True) self.w.doLibCheckBox.set(True) self.w.doFeaturesCheckBox.set(True) self.w.doGlyphsText.set("") self.w.doGlyphMarksCheckBox.set(False) self.w.doGlyphMasksCheckBox.set(False) self.w.doGlyphHintsCheckBox.set(False) glyphs = None elif mode == quickMode_export_currentFont_selectedGlyphs: # import self.w.doImportCheckBox.set(False) self.w.saveVFBCheckBox.set(False) self.w.closeVFBCheckBox.set(False) # export self.w.doExportCheckBox.set(True) self.w.exportCurrentFontCheckBox.set(True) self.w.exportAllOpenFontsCheckBox.set(False) self.w.exportFormatVersion1CheckBox.set(False) self.w.exportFormatVersion2CheckBox.set(True) # destination self.w.destinationNewFilesCheckBox.set(False) self.w.destinationExistingFilesCheckBox.set(True) # parts self.w.doFontInfoCheckBox.set(False) self.w.doKerningCheckBox.set(False) self.w.doGroupsCheckBox.set(False) self.w.doLibCheckBox.set(False) self.w.doFeaturesCheckBox.set(False) self.w.doGlyphsText.set("") self.w.doGlyphMarksCheckBox.set(False) self.w.doGlyphMasksCheckBox.set(False) self.w.doGlyphHintsCheckBox.set(False) font = CurrentFont() if font is None: glyphs = None elif not len(font.selection): glyph = CurrentGlyph() if glyph is None: glyphs = None else: glyphs = [glyph.name] else: glyphs = font.selection glyphs.sort() else: return # update enabled states if self.w.doImportCheckBox.get(): self.mode = "import" else: self.mode = "export" self._modeChange() # update glyph list self.glyphs = glyphs self._updateGlyphsText()
import sys sys.path.append('/Users/alexander/PycharmProjects/CustomControls') import tdReport from robofab.world import CurrentFont, CurrentGlyph font = CurrentFont() gselected = CurrentGlyph() TOFL_MARK = (0.4, 1.0, 0.4, 1.0) EXPORTED = (0.4, 1.0, 0.4, 0.1) EXCEPT_MARK = (1.0, 0.8, 0.4, 1.0) file_ext = 'toFl' path_exp = font.path.replace('.ufo', '') # filename = font.filename report = tdReport.Report(file=path_exp, ext='toFL', process='Export selected glyphs to FontLab') print 'Selected glyph: ', gselected.name, 'marked as', gselected.mark names = [] for gf in CurrentFont(): if gf.mark == gselected.mark: names.append(gf.name) report.add(gf.name) print names print 'Glyph list saved as: ' + path_exp + '.' + file_ext report.save()
#FLM: AT Copy widths to open fonts # Copy the selected widths to other fonts from robofab.world import CurrentFont, AllFonts, CurrentGlyph fonts = AllFonts() forigen = CurrentFont() sel = forigen.selection def copiaWidth(myWidth, gtarget): anchoFinal = gtarget.width anchoActual = myWidth anchoDif = anchoActual - anchoFinal anchoSide = anchoDif / 2 gtarget.leftMargin = gtarget.leftMargin + anchoSide gtarget.rightMargin = gtarget.rightMargin + anchoSide gtarget.width = myWidth print str(myWidth) + " > " + str(gtarget.width) for f in fonts: for gname in sel: if gname in f: destino = f[gname] origen = forigen[gname] print f[gname] destino.mark = origen.mark copiaWidth(origen.width, destino) f.update() print sel
return False else: return True def getLayer(nakedFont, message): numberOfLayers = nakedFont[0].layers_number - 1 layers = [] while numberOfLayers >= 0: layers.append(numberOfLayers) numberOfLayers = numberOfLayers - 1 whichLayer = OneList(layers, message) return int(whichLayer) fontToChange = CurrentFont() if not hasMM(fontToChange.naked()): Message('Font needs to be MM') else: orignalMetricsFont = OpenFont(None, "Which font's sidebearings do you want?") orignalMetrics = {} tickCount = len(orignalMetricsFont) bar = ProgressBar('Getting metrics', tickCount) tick = 0 if hasMM(orignalMetricsFont.naked()): layer = getLayer(orignalMetricsFont.naked(), 'Which layer do you want?') for glyph in orignalMetricsFont: advanceWidth = int(glyph.naked().GetMetrics(layer).x)
# robothon06 from robofab.world import CurrentFont # We need to import a class with a different # implementation for the glyph object. # It looks a bit odd, but this is how it is done from robofab.objects.objectsRF import RGlyph as _RGlyph f = CurrentFont() # pick two compatible glyphs as masters m1 = f["A"] m2 = f["B"] # make a new glyph object from this other glyph class g = _RGlyph() # interpolation factor which is bound to make floats oddFactor = 0.2382345 # go! g.interpolate(oddFactor, m1, m2) # let's have a look at the raw results for contour in g: for pt in contour.points: print "float", pt.x, pt.y # a glyph can round itself off: g.round()
def makeWords(self, sender=None): """Parse user input, save new values to prefs, compile and display the resulting words. I think this function is too long and bloated, it should be taken apart. ######## """ global warned self.f = CurrentFont() if self.f is not None: self.fontChars, self.glyphNames = self.fontCharacters(self.f) self.glyphNamesForValues = { self.fontChars[i]: self.glyphNames[i] for i in range(len(self.fontChars)) } else: self.fontChars = [] self.glyphNames = [] self.wordCount = self.getIntegerValue(self.g1.wordCount) self.minLength = self.getIntegerValue(self.g1.minLength) self.maxLength = self.getIntegerValue(self.g1.maxLength) self.case = self.g1.case.get() self.customCharset = [] charset = self.g1.base.get() self.limitToCharset = True if charset == 0: self.limitToCharset = False elif charset == 2: # use selection if len(self.f.selection) == 0: # nothing selected Message( "word-o-mat: No glyphs were selected in the font window. Will use any characters available in the current font." ) self.g1.base.set(1) # use font chars else: try: self.customCharset = [] for gname in self.f.selection: if self.f[gname].unicode is not None: try: self.customCharset.append( unichr(int(self.f[gname].unicode))) except ValueError: pass except AttributeError: pass elif charset == 3: # use mark color ''' c = self.g1.colorWell.get() if c is None: pass elif c.className() == "NSCachedWhiteColor": # not set, corresponds to mark color set to None c = None ''' self.customCharset = [] ''' self.reqMarkColor = (c.redComponent(), c.greenComponent(), c.blueComponent(), c.alphaComponent()) if c is not None else None for g in self.f: if g.mark == self.reqMarkColor: try: self.customCharset.append(unichr(int(g.unicode))) except: pass ''' if len(self.customCharset) == 0: Message( "word-o-mat: Found no glyphs that match the specified mark color. Will use any characters available in the current font." ) self.g1.base.set(1) # use font chars self.toggleColorSwatch(0) self.matchMode = "text" if self.g2.matchMode.get( ) == 0 else "grep" # braucht es diese zeile noch? self.requiredLetters = self.getInputString( self.g2.textMode.mustLettersBox, False) self.requiredGroups[0] = self.getInputString( self.g2.textMode.group1box, True) self.requiredGroups[1] = self.getInputString( self.g2.textMode.group2box, True) self.requiredGroups[2] = self.getInputString( self.g2.textMode.group3box, True) self.matchPattern = self.g2.grepMode.grepBox.get() self.banRepetitions = self.g3.checkbox0.get() self.outputWords = [] # initialize/empty self.source = self.g1.source.get() languageCount = len(self.textfiles) if self.source == languageCount: # User Dictionary self.allWords = self.dictWords["user"] elif self.source == languageCount + 1: # Use all languages for i in range(languageCount): # if any language: concatenate all the wordlists self.allWords.extend(self.dictWords[self.textfiles[i]]) elif self.source == languageCount + 2: # Custom word list try: if self.customWords != []: self.allWords = self.customWords else: self.allWords = self.dictWords["ukacd"] self.g1.source.set(0) except AttributeError: self.allWords = self.dictWords["ukacd"] self.g1.source.set(0) else: # language lists for i in range(languageCount): if self.source == i: self.allWords = self.dictWords[self.textfiles[i]] # store new values as defaults markColorPref = self.reqMarkColor if self.reqMarkColor is not None else "None" extDefaults = { "wordCount": self.wordCount, "minLength": self.minLength, "maxLength": self.maxLength, "case": self.case, "limitToCharset": self.writeExtDefaultBoolean(self.limitToCharset), "source": self.source, "matchMode": self.matchMode, "matchPattern": self.matchPattern, # non compiled string "markColor": markColorPref, } for key, value in extDefaults.iteritems(): setExtensionDefault("com.ninastoessinger.word-o-mat." + key, value) # go make words if self.checkInput(self.limitToCharset, self.fontChars, self.customCharset, self.requiredLetters, self.minLength, self.maxLength, self.case) == True: checker = wordcheck.wordChecker(self.limitToCharset, self.fontChars, self.customCharset, self.requiredLetters, self.requiredGroups, self.matchPatternRE, self.banRepetitions, self.minLength, self.maxLength, matchMode=self.matchMode) for i in self.allWords: if len(self.outputWords) >= self.wordCount: break else: w = choice(self.allWords) if self.case == 1: w = w.lower() elif self.case == 2: # special capitalization rules for Dutch IJ # this only works when Dutch is selected as language, not "any". try: ijs = ["ij", "IJ", "Ij"] if self.languageNames[ self.source] == "Dutch" and w[:2] in ijs: wNew = "IJ" + w[2:] w = wNew else: w = w.title() except IndexError: w = w.title() elif self.case == 3: # special capitalization rules for German double s if u"ß" in w: w2 = w.replace(u"ß", "ss") w = w2 w = w.upper() if checker.checkWord(w, self.outputWords): self.outputWords.append(w) # output if len(self.outputWords) < 1: Message("word-o-mat: no matching words found <sad trombone>") else: joinString = " " if self.g3.listOutput.get() == True: joinString = "\\n" self.outputWords = self.sortWordsByWidth(self.outputWords) outputString = joinString.join(self.outputWords) try: sp = OpenSpaceCenter(CurrentFont()) sp.setRaw(outputString) except: if warned == False: Message( "word-o-mat: No open fonts found; words will be displayed in the Output Window." ) warned = True print "word-o-mat:", outputString