Exemple #1
0
 def _importMasters_button_callback(self, sender):
     # Import UFO(s) file
     getFile(messageText=u"Add new UFO",
             allowsMultipleSelection=True,
             fileTypes=["ufo"],
             parentWindow=self.w,
             resultCallback=self._importMasters_callback)
 def openFile(self, sender=None):
     directory = fileName = None
     if self.font is not None and self.font.path is not None:
         if self.fileNameKey in self.font.lib.keys():
             fileName = self.font.lib.get(self.fileNameKey, "")
             fileName += ".glyphConstruction"
             directory = os.path.dirname(self.font.path)
             fileName = os.path.join(directory, fileName)
             directory = None
     getFile(fileTypes=["glyphConstruction"], parentWindow=self.w.getNSWindow(), directory=directory, fileName=fileName, resultCallback=self._openFile)
Exemple #3
0
 def _projects_popUpButton_callback(self, sender):
     sel = sender.get()
     if sel == len(self.project_popUpButton_list)-1:
         getFile(messageText = u"Load a project...",
             allowsMultipleSelection = False,
             fileTypes = ["roboCJKproject", "json"],
             parentWindow = self.w,
             resultCallback = self._importProject_callback)
     else:
         self.projectName = self.project_popUpButton_list[sel]
         readCurrentProject(self, self.projects[self.projectName])
         self._setUI()
     self.updateViews()
Exemple #4
0
 def openFile(self, sender=None):
     directory = fileName = None
     if self.font is not None and self.font.path is not None:
         if self.fileNameKey in self.font.lib.keys():
             fileName = self.font.lib.get(self.fileNameKey, "")
             fileName += ".glyphConstruction"
             directory = os.path.dirname(self.font.path)
             fileName = os.path.join(directory, fileName)
             directory = None
     getFile(fileTypes=["glyphConstruction"],
             parentWindow=self.w.getNSWindow(),
             directory=directory,
             fileName=fileName,
             resultCallback=self._openFile)
def main():
    global Bounds
    paths = getFile(title="Please select .svg files", allowsMultipleSelection=True, fileTypes=["svg"])

    if paths is None:
        return
    for path in paths:
        name = basename(path)
        name = splitext(name)[0]
        f = CurrentFont()
        g = f[name]
        if g is None:
            g = f.newGlyph(name)
        pen = g.getPen()
        dom = minidom.parse(path)
        SVG = dom.getElementsByTagName("svg")[0]
        Bounds = SVG.getAttribute("viewBox").split(" ")
        if len(Bounds) == 4:
            Bounds = [float(Value) for Value in Bounds]
        else:
            Width = SVG.getAttribute("width")
            Height = SVG.getAttribute("height")
            if Width and Height:
                Bounds = [0, 0, float(Width), float(Height)]
        for node in dom.getElementsByTagName("svg")[0].childNodes:
            drawSVGNode(pen, node, NSAffineTransform.alloc().init())
Exemple #6
0
def main():
    global Bounds
    paths = getFile(title="Please select .svg files",
                    allowsMultipleSelection=True,
                    fileTypes=["svg"])

    if paths is None:
        return
    for path in paths:
        name = basename(path)
        name = splitext(name)[0]
        f = CurrentFont()
        g = f[name]
        if g is None:
            g = f.newGlyph(name)
        pen = g.getPen()
        dom = minidom.parse(path)
        SVG = dom.getElementsByTagName("svg")[0]
        Bounds = SVG.getAttribute('viewBox').split(" ")
        if (len(Bounds) == 4):
            Bounds = [float(Value) for Value in Bounds]
        else:
            Width = SVG.getAttribute("width")
            Height = SVG.getAttribute("height")
            if Width and Height:
                Bounds = [0, 0, float(Width), float(Height)]
        for node in dom.getElementsByTagName("svg")[0].childNodes:
            drawSVGNode(pen, node, NSAffineTransform.alloc().init())
Exemple #7
0
 def changeSourceCallback(self, sender):
     """On changing source/wordlist, check if a custom word list should be loaded."""
     customIndex = len(self.textfiles) + 2
     if sender.get() == customIndex:  # Custom word list
         try:
             filePath = getFile(
                 title="Load custom word list",
                 messageText=
                 "Select a text file with words on separate lines",
                 fileTypes=["txt"])[0]
         except TypeError:
             filePath = None
             self.customWords = []
             print(
                 "word-o-mat: Input of custom word list canceled, using default"
             )
         if filePath is not None:
             fo = codecs.open(filePath, mode="r", encoding="utf-8")
             lines = fo.read()
             fo.close()
             # self.customWords = lines.splitlines()
             self.customWords = []
             for line in lines.splitlines():
                 w = line.strip()  # strip whitespace from beginning/end
                 self.customWords.append(w)
Exemple #8
0
    def loadStatusCallback(self, sender):
        kerningStatusPath = getFile(title='Load Kerning Status JSON file',
                                    allowsMultipleSelection=False)[0]

        if os.path.splitext(os.path.basename(kerningStatusPath))[1] == '.json':
            jsonFile = open(kerningStatusPath, 'r')
            statusDictionary = json.load(jsonFile)
            jsonFile.close()

            # unwrap dictionaries
            self.kerningWordsDB = statusDictionary['kerningWordsDB']
            self.kerningTextBaseNames = statusDictionary['kerningTextBaseNames']
            self.activeKerningTextBaseName = statusDictionary['activeKerningTextBaseName']
            self.wordsWorkingList = statusDictionary['wordsWorkingList']
            self.wordsDisplayList = statusDictionary['wordsDisplayList']
            self.activeWord = statusDictionary['activeWord']
            self.wordFilter = statusDictionary['wordFilter']

            # adjust controllers
            self.kerningVocabularyPopUp.setItems(self.kerningTextBaseNames)
            self.kerningVocabularyPopUp.set(self.kerningTextBaseNames.index(self.activeKerningTextBaseName))
            self.wordsListCtrl.set(self.wordsDisplayList)

            for indexRow, eachRow in enumerate(self.wordsDisplayList):
                if eachRow['word'] == self.activeWord:
                    self.wordsListCtrl.setSelection([indexRow])
                    break

            self._updateInfoCaption()
            self.callback(self)

        else:
            message('No JSON, no party!', 'Chosen file is not in the right format')
    def choose_file(self, sender):
        filepath = getFile("Choose a .txt or .pdf document to use as a license",
                           "Select License",
                           fileTypes=("txt", "md", "pdf"))

        if filepath is not None:
            self.storage.store(filepath[0])
            self.filepath = filepath[0]
Exemple #10
0
    def choose_file(self, sender):
        filepath = getFile("Choose a .txt or .pdf document to use as a license",
                           "Select License",
                           fileTypes=("txt", "md", "pdf"))

        if filepath is not None:
            self.storage.store(filepath[0])
            self.filepath = filepath[0]
Exemple #11
0
 def loadHangulModuleDataCallback(self, sender):
     paths = getFile()
     path = paths[0]
     with open(path, 'r', encoding='utf-8') as file:
         data = json.load(file)
     self.hangulModule.initializeWithExternalData(data)
     for e in ['userNames', 'combinations']:
         getattr(self.w, e).setUI()
     for pos in ['initial', 'medial', 'final']:
         getattr(self.w.groups, pos).setUI()
Exemple #12
0
def importFontInfoFromUFOtoCurrentFont():
    aFontPath = getFile(messageText='Please, choose a UFO file',
                        fileTypes=['ufo'])[0]
    if aFontPath.endswith('.ufo'):
        if version[0] == '2':
            sourceFont = OpenFont(aFontPath, showInterface=False)
        else:
            sourceFont = OpenFont(aFontPath, showUI=False)
        sourceFontInfos = sourceFont.info.asDict()
        for eachAttribute, eachValue in sourceFontInfos.items():
            setattr(CurrentFont().info, eachAttribute, eachValue)
Exemple #13
0
 def openDocument_(self, sender):
     result = getFile(
         allowsMultipleSelection=True, fileTypes=fileTypes +
         ["gggls"])  # resultCallback=self.getFileResultCallback_)
     # NOTE: ideally we would use a result callback, but vanilla's
     # getFile() only supports result callbacks in the presence of
     # parent window, which we obviously do not have here.
     # Also note: we can't use NSDocumentController's openDocument_
     # as it assumes one file per document.
     if result:
         self.application_openFiles_(None, result)
 def get_otf_2_callback(self, sender):
     otf_2 = getFile(
         messageText='choose a first .otf font',
         title=self.title,
         allowsMultipleSelection=False)
     if otf_2 is not None:
         otf_2 = otf_2[0]
         if len(otf_2) > 0:
             self.otf_2 = otf_2
             if os.path.exists(self.otf_2):
                 setExtensionDefault('%s.otf_2' % self.extension_key, self.otf_2)
                 self.w.otf_2_status.set('%s' % unichr(10003))
Exemple #15
0
    def open(self):
        """Opens a different script by calling up the get file dialog."""
        paths = getFile(messageText='Please select your script',
                        title='Select a script.',
                        allowsMultipleSelection=False,
                        fileTypes=('py', ))

        if paths is not None:
            self.scriptPath = paths[0]
            self.scriptFileName = self.scriptPath.split('/')[-1]
            self.scriptName = self.scriptFileName.split('.')[0]
            self.window.path.set(self.scriptPath)
            self.run()
Exemple #16
0
    def loadFromTableCallback(self, sender):
        loadingPath = getFile("Select table with linked sidebearings")
        if loadingPath is None:
            return None

        with open(loadingPath[0], 'r') as linksTable:
            rawTable = [item for item in linksTable.readlines()]

        changedItems = []
        toBeLinksList = list(self.selectedFont.glyphOrder)
        for indexRow, eachRow in enumerate(rawTable):
            lft, lftActive, servant, rgtActive, rgt = [
                item.strip() for item in eachRow.split('\t')
            ]
            servantResult = self._isGlyphNameAllowed(servant)
            lftResult = self._isGlyphNameAllowed(lft)
            rgtResult = self._isGlyphNameAllowed(rgt)

            if all([servantResult, lftResult, rgtResult]) is False:
                message(
                    'Line {} contains a mistake'.format(indexRow + 1),
                    'One or more glyphs [lft:<{}> servant:<{}> rgt:<{}>] are not allowed in this font'
                    .format(lft, servant, rgt))
                return None

            if servant in toBeLinksList:
                servantIndex = toBeLinksList.index(servant)
                toBeLinksList[servantIndex] = {
                    'lft': lft,
                    'lftActive': True if lftActive == 'True' else False,
                    'servant': servant,
                    'rgt': rgt,
                    'rgtActive': True if rgtActive == 'True' else False
                }
                changedItems.append(servantIndex)

        for eachUnchangedIndex in [
                ii for ii in range(len(toBeLinksList))
                if ii not in changedItems
        ]:
            toBeLinksList[eachUnchangedIndex] = {
                'lft': '',
                'lftActive': False,
                'servant': toBeLinksList[eachUnchangedIndex],
                'rgt': '',
                'rgtActive': False
            }

        self.w.linksList.set(toBeLinksList)
        self._compareLibsToList()
Exemple #17
0
 def changeSourceCallback(self, sender):
     customIndex = len(self.textfiles) + 1
     if sender.get() == customIndex: # Custom word list
         try:
             filePath = getFile(title="Load custom word list", messageText="Select a text file with words on separate lines", fileTypes=["txt"])[0]
         except TypeError:
             filePath = None
             self.customWords = []
             print "word-o-mat: Input of custom word list canceled, using default"
         if filePath is not None:
             fo = codecs.open(filePath, mode="r", encoding="utf-8")
             lines = fo.read()
             fo.close()
             
             self.customWords = lines.splitlines()
Exemple #18
0
 def convertButtonCallback(self, sender):
     if self.chosenMode == 'Single File':
         inputPath = getFile('Choose the file to convert')[0]
         if inputPath.endswith('.vfb') or inputPath.endswith('.ufo'):
             executeCommand(['vfb2ufo', '-fo', inputPath], shell=True)
         else:
             message('input file path is not correct')
     else:
         inputFolder = getFolder('Choose a folder with files to convert')[0]
         if inputFolder:
             for eachPath in catchFilesAndFolders(inputFolder,
                                                  self.chosenSuffix):
                 executeCommand(['vfb2ufo', '-fo', eachPath], shell=True)
         else:
             message('input folder path is not correct')
 def changeSourceCallback(self, sender):
     """On changing source/wordlist, check if a custom word list should be loaded."""
     customIndex = len(self.textfiles) + 2
     if sender.get() == customIndex: # Custom word list
         try:
             filePath = getFile(title="Load custom word list", messageText="Select a text file with words on separate lines", fileTypes=["txt"])[0]
         except TypeError:
             filePath = None
             self.customWords = []
             print("word-o-mat: Input of custom word list canceled, using default")
         if filePath is not None:
             with codecs.open(filePath, mode="r", encoding="utf-8") as fo:
                 lines = fo.read()
             # self.customWords = lines.splitlines()
             self.customWords = []
             for line in lines.splitlines():
                 w = line.strip() # strip whitespace from beginning/end
                 self.customWords.append(w)
def main():
    global Bounds

    g = CurrentGlyph()
    print g
    pen = g.getPen()

    path = getFile(title="Please select a .svg", fileTypes=["svg"])
    if path:
        dom = minidom.parse(path[0])
        SVG = dom.getElementsByTagName("svg")[0]
        Bounds = SVG.getAttribute('viewBox').split(" ")
        if (len(Bounds) == 4):
            Bounds = [float(Value) for Value in Bounds]
        else:
            Width = SVG.getAttribute("width")
            Height = SVG.getAttribute("height")
            if Width and Height:
                Bounds = [0, 0, float(Width), float(Height)]
        for node in dom.getElementsByTagName("svg")[0].childNodes:
            drawSVGNode(pen, node, NSAffineTransform.alloc().init())
Exemple #21
0
def main():
	global Bounds
	
	g = CurrentGlyph()
	print g
	pen = g.getPen()
	
	path = getFile(title="Please select a .svg", fileTypes=["svg"])
	if path:
		dom = minidom.parse(path[0])
		SVG = dom.getElementsByTagName("svg")[0]
		Bounds = SVG.getAttribute('viewBox').split(" ")
		if (len(Bounds) == 4):
			Bounds = [float(Value) for Value in Bounds]
		else:
			Width = SVG.getAttribute("width")
			Height = SVG.getAttribute("height")
			if Width and Height:
				Bounds = [0, 0, float(Width), float(Height) ]
		for node in dom.getElementsByTagName("svg")[0].childNodes:
			drawSVGNode(pen, node, NSAffineTransform.alloc().init())
Exemple #22
0
 def _loadGlyphsCompositionData_button_callback(self, sender):
     getFile(messageText=u"Load Glyph Composition Data",
             allowsMultipleSelection=False,
             fileTypes=["json"],
             parentWindow=self.w,
             resultCallback=self._loadGlyphsCompositionData_callback)
Exemple #23
0
 def get_file_callback(self, sender):
     self.ufo_path = getFile()[0]
Exemple #24
0
 def getFileAccessoryView(self, sender):
     import vanilla
     view = vanilla.Box((0, 0, 200, 75))
     view.checkBox = vanilla.CheckBox((10, 10, 100, 22), "checked")
     print("result", dialogs.getFile(accessoryView=view))
 def get_file_callback(self, sender):
     returned_path = getFile()
     if returned_path:
         self.list_path = returned_path[0]
Exemple #26
0
# The ID and range of a sample spreadsheet.
SPREADSHEET_ID = '1-LcFQ2xjnI8GemKExw2xQ5ex8M2Xh-sD6TxMV96EGrY'
RANGE_NAME = 'Inputs!A2:H'

# if we are not in robofont, use fontparts to parse UFO
try:
    test = OpenFont
except:
    from fontParts.world import OpenFont
    
# if we can get vanilla, select the designspace
# if not, use the commandline argument
try:
    from vanilla.dialogs import getFolder, getFile
    designspacePath = getFile('Get designspace file')[0]
except:
    designspacePath = sys.argv[1]
    


doc = DesignSpaceDocument()
doc.read(designspacePath)
designspaceFileName = os.path.split(designspacePath)[1]
for source in doc.sources:
    if source.copyInfo:
        f = OpenFont(source.path)
        measurements = {}
        for gname in f.glyphOrder:
            g = f[gname]
            
Exemple #27
0
 def btnRightLoadSetCallback(self, sender):
     filename = getFile(messageText='Select text file', title='title')
     if filename and filename[0]:
         self.loadSetOfGlyphs(filename=filename[0], direction='R')
 def getEncodingCallback(self, sender):
     getFile(parentWindow=self.w, fileTypes=['enc', 'Enc'], resultCallback=self.processEncodingCallback)
Exemple #29
0
 def getFile(self, sender):
     print("result", dialogs.getFile())
 def loadMatrixFile(self, sender):
     pathToLoad = getFile(fileTypes=['txt'], allowsMultipleSelection=False, resultCallback=self.loadMatrix, parentWindow=self.w)
Exemple #31
0
 def getFileSheet(self, sender):
     dialogs.getFile(parentWindow=self.w, resultCallback=self.dummyCallback)
Exemple #32
0
 def _loadProject_button_callback(self, sender):
     getFile(messageText=u"Load a project",
             allowsMultipleSelection=True,
             fileTypes=["roboCJKproject", "json"],
             parentWindow=self.w,
             resultCallback=self._importProject_callback)
Exemple #33
0
 def get_extension(self, sender):
     getFile(fileTypes=['roboFontExt'],
             parentWindow=self.parent.w,
             resultCallback=self.import_extension)
 def get_file_callback(self, sender):
     self.ufo_path = getFile()[0]
Exemple #35
0
print
print "makeVAR v%s" % __version__
print __doc__
print


from vanilla.dialogs import getFile
import sys
import os
import os.path
import subprocess


# get designspace file
getDesignspace = getFile('Select the .designspace file:', fileTypes=['designspace'])
if getDesignspace:
    designspacePath = getDesignspace[0]
    currentFolder = os.path.dirname(designspacePath)
    os.chdir(currentFolder)

    # output
    outputFilePath = os.path.join(currentFolder, "mkvar_output.log")
    f = open(outputFilePath, 'w')
    sep = '-' * 57 + '\n'
    report = [sep, 'Generate variable font using\n%s\n\n' % designspacePath, sep]

    # command stuff
    command = 'fontmake -m %s -o variable' % designspacePath
    popen = subprocess.Popen(command, shell=True, stdout=f, stderr=subprocess.PIPE)
Exemple #36
0
 def getUfo(self, sinder):
     ufoPath = getFile()[0]
     self.ufo = OpenFont(ufoPath, showUI=False)
     PostNotification('doodle.updateGlyphView')
 def getFile(self, sender):
     path = getFile(fileTypes=['py'], allowsMultipleSelection=False, resultCallback=self.loadFilePath, parentWindow=self.filterSheet)
# See https://github.com/robotools/vanilla/blob/master/Lib/vanilla/dialogs.py
from vanilla.dialogs import getFile, putFile

# Get a gif or png image
filePath = getFile(messageText="Get a file", fileTypes=['gif', 'png'])
print("filePath:")
print(filePath)

# Draw image on canvas (dumb I know)
image(filePath[0], (0, 0))

# Save the file, only allow it to be a PDF or Gif, if no file extension is
# given, defaults to PDF as it's first in the fileTypes list
savePath = putFile(messageText="Select a spot to save a file",
                   fileTypes=['pdf', 'gif'])
print("savePath:")
print(savePath)

saveImage(savePath)
Exemple #39
0
 def get_extension(self, sender):
     getFile(fileTypes=['roboFontExt'],
             parentWindow=self.parent.w,
             resultCallback=self.import_extension)
Exemple #40
0
 def get_file_callback(self, sender):
     returned_path = getFile()
     if returned_path:
         self.list_path = returned_path[0]