Beispiel #1
0
def make_component_current_font():
    """ Makes component of glyphs in current font. """
    f = CurrentFont()
    keys = f.keys()

    for key in keys:
        name = 'uni%x' %f[key].unicode
        f.newGlyph(name)
        f[name].appendComponent(key)
        f[name].width = f[key].width
        f[name].leftMargin = f[key].leftMargin
        f[name].rightMargin = f[key].rightMargin
        f[name].unicodes = f[key].unicodes
Beispiel #2
0
	def checkLangauge(self):
		"""
			현재 띄워져 있는 폰트의 첫번째 glyphOrder를 참고하여 한글 폰트인지 한자 폰트인지 판별한다.
			한자, 한글이 섞여있거나 첫번째 glyphOrder에 해당하는 글자에 이상이 있으면 정확한 판별이 되지 않는다.

			수행 도중 알 수 없는 이유로 에러가 나면 None으로 세팅
		"""
		font = CurrentFont()

		idx = 0
		
		#만약 ufo파일에 글자 수가 10개 미만인 경우 고려 + 첫번째 글리프 오더가 이상한 경우 고려
		for idx in range(min(len(font.glyphOrder),10)):
		    try:
		        int(font.glyphOrder[idx][3:],16)
		        break
		    except ValueError:
		        continue    

		try:
			print(font.glyphOrder[idx][3:])
			if not 0xAC00 <= int(font.glyphOrder[idx][3:], 16) <= 0xD7A3:
				setExtensionDefault(self.registerKey+".korean", False)
			else:
				setExtensionDefault(self.registerKey+".korean", True)
		except Exception as e:
			print("언어(한글, 한자) 판별 중 예외가 발생했습니다.")
			print(e)
			setExtensionDefault(self.registerKey+".korean", None)
Beispiel #3
0
def ufo2mf(destPath):
	f = CurrentFont()

	DIR_UFO = f.path+"/glyphs" 

	DIR_METAFONT_RADICAL = destPath+"/radical.mf"
	DIR_METAFONT_COMBINATION = destPath+"/combination.mf"
		
	print("Target:", DIR_UFO)
	print("Destination Path:", destPath)
	# Remove exist Metafont file for renew
	try:
		os.remove(DIR_METAFONT_RADICAL)
		os.remove(DIR_METAFONT_COMBINATION)
	except:
		notthing = 0

	# Get glyphs from UFO and Convert to Metafont
	glyphList = [f for f in os.listdir(DIR_UFO) if fnextension (f) == 'glif']
	# Get font width
	fontWidth = getFontWdith(DIR_UFO, glyphList)
	for glyph in glyphList:
		convertToMetafont(glyph, DIR_UFO, DIR_METAFONT_RADICAL, DIR_METAFONT_COMBINATION, fontWidth)

	return None
def find_overlap_contour_current_font():
    """ Finds overlapping contours in the current font.

    Returns:
        overlap_set:: set
            A set of overlapping RContour objects in the current font.
    """
    font = CurrentFont()
    overlap_set = set()
    for o in font.glyphOrder:
        glyph = font.getGlyph(o)
        for contour in glyph.contours:
            if _is_overlap_other_contour(glyph.contours, contour):
                overlap_set.add((contour, contour.index))

    return overlap_set
Beispiel #5
0
def name_attr():
    f = CurrentFont()
    path = f.path + '/glyphs'
    files = os.listdir(path)

    for file in files:
        print(file)
        tree = parse(path + "/" + file)
        glyph = tree.getroot()
        outline = glyph.find("outline")
        if outline == None:
            continue
        contours = outline.getchildren()

        for contour in contours:
            for point in contour.getchildren():
                name = (point.get("name"))
                if name != None:
                    name = '{' + name.replace("'", '"') + '}'
                    name = json.loads(name)
                    for attr in list(name.items()):
                        point.attrib[attr[0]] = attr[1]

                    try:
                        del point.attrib['name']
                    except:
                        pass

                    tree.write(path + "/" + file, encoding="utf-8")
    print("--------------------End name_attr()--------------------")
 def btnApplyCallback(self, info):
     if not self.w.chkBox.get():
         font = CurrentFont()
         self.switchCharset(font)
     else:
         for font in AllFonts():
             self.switchCharset(font)
Beispiel #7
0
	def rollbackAttribute(self, sender):

		restoreStack = getExtensionDefault(DefaultKey + ".restoreStack")
		
		if restoreStack is None or restoreStack.front == restoreStack.rear:
			restoreStack.print()
			Message("복원할 수 없습니다.")
			return

		target = restoreStack.rollback()
	
		if target is None:
			Message("복원할 수 없습니다.")
			return 

		for element in target:
			element[0].name = element[1]

		restoreStack.print()
		CurrentFont().update()
		CurrentFont().save(self.testPath)
Beispiel #8
0
	def restoreAttribute(self, sender):

		restoreStack = getExtensionDefault(DefaultKey + ".restoreStack")

		
		if restoreStack is None or restoreStack.isEmpty() is True:
			restoreStack.print()
			Message("더 이상 되돌릴 수 없습니다.")
			return

		top = restoreStack.pop()
		if top is None:
			restoreStack.print()
			Message("더 이상 되돌릴 수 없습니다.")
			return

		for element in top:
			element[0].name = element[1]

		restoreStack.print()
		CurrentFont().update()
		CurrentFont().save(self.testPath)
Beispiel #9
0
def ufo2mf(dest_path, ufo_path=None, logs=True):
    """ Converts UFO format to METAFONT format.

    Args:
        dest_path:: str
        ufo_path:: str (default is None)
        logs:: bool
    """
    if ufo_path is None:
        font = CurrentFont()
    else:
        font = OpenFont(os.path.abspath(ufo_path), showInterface=False)
    dest_path = os.path.abspath(dest_path)

    with open(os.path.join(dest_path, mfc.RADICAL)) as radical_mf, \
            open(os.path.join(dest_path, mfc.COMBINATION)) as combination_mf:
        if logs:
            print(
                "====================== Start ufo2mf() ======================")
            # print("Date:")
            print("Target:", font.path)
            print("Destination Path:", dest_path)
            print("Radical Path:", radical_mf)
            print("Combination Path:", combination_mf)

        # Remove exist Metafont file for renew
        try:
            os.remove(radical_mf)
            os.remove(combination_mf)
        except:
            pass

        for key in font.keys:
            glyph = font.getGlyph(key)
            glyph2mf(glyph, radical_mf, combination_mf, logs)

    if logs:
        print("======================= End ufo2mf() =======================")
Beispiel #10
0
def launchFontTool():

	currentFont = CurrentFont()
	if currentFont is not None:
		# 전에 열었던 폰트 파일과 같다면 굳이 물어볼 필요가 없다. (getExtensionDefault가 잘 안먹히는 오류가 있긴 함)
		if currentFont == getExtensionDefault(DefaultKey+".font"):
			return getExtensionDefault(DefaultKey+".testPath"), currentFont
		
		testPath = currentFont.path

		if testPath is None:
			Message('폰트 파일 경로를 알 수 없습니다.'
				, informativeText='.ttf의 경우, 폰트 파일 경로를 알 수 없어 ufo 변환을 해야 합니다.\n.ttf를 .ufo로 바꾸려면 [File]-[Save]를 눌러주세요')
			return None, None

	return testPath, currentFont
Beispiel #11
0
		def __init__ (self):
			self.w = Window((300, 400), "Choose exception", minSize = (100, 100))
			hGRPcontrols = 85
			yInfoControl = 5
			wW = 500
			hW = 350
			self.font = CurrentFont()
			self.hashKernDic = TDHashKernDic(self.font)
			self.flagAutoKern = True
			self.pair = ['A', 'H']
			# self.pair = ['A', 'afii10071']
			# self.pair = ['Lslash', 'Tbar']


			self.w.btnOpen = Button(((wW / 2) + 2, hW - 22, -10, 17), "Apply", callback = self.btnOpenCallback,
			                        sizeStyle = 'small')

			self.w.open()
Beispiel #12
0
def dependAll(base_point, refer_point, dependType):
    f = CurrentFont()
    g = CurrentGlyph()

    pointXList = []
    pointYList = []

    ######## data for comparing

    for contour in g:  ## indexing raw data
        for point in contour.points:

            if point.x not in pointXList:
                pointXList.append(point.x)

            if point.y not in pointYList:
                pointYList.append(point.y)

    pointXList.sort()
    pointYList.sort()

    base_index = {}
    refer_index = {}

    for i, x in enumerate(pointXList):
        if x == base_point.x:
            base_index['x'] = i
        if x == refer_point.x:
            refer_index['x'] = i

    for i, y in enumerate(pointYList):
        if y == base_point.y:
            base_index['y'] = i
        if y == refer_point.y:
            refer_index['y'] = i

    for glyph in f:

        glyphXList = []
        glyphYList = []

        xcount = 0
        ycount = 0

        refer = None
        base = None

        if len(glyph) != len(g):
            continue

        for contour in glyph:
            for point in contour.points:

                if point.x not in glyphXList:
                    glyphXList.append(point.x)
                    xcount += 1

                if point.y not in glyphYList:
                    glyphYList.append(point.y)
                    ycount += 1

        if xcount != len(pointXList) or ycount != len(pointYList):
            continue

        glyphYList.sort()
        glyphXList.sort()

        for contour in glyph:
            for point in contour.points:
                if point.x == glyphXList[base_index[
                        'x']] and point.y == glyphYList[base_index['y']]:
                    base = point

                if point.x == glyphXList[refer_index[
                        'x']] and point.y == glyphYList[refer_index['y']]:
                    refer = point

        if refer is not None and base is not None and get_attr(
                refer, 'penPair') is not None:
            if dependType == 'x':
                set_attr(base, "dependX",
                         get_attr(refer, 'penPair').replace('z', 'x'))
            elif dependType == 'y':
                set_attr(base, "dependY",
                         get_attr(refer, 'penPair').replace('z', 'x'))
Beispiel #13
0
 def showFontEditorSpaceStation(self):
     font = CurrentFont()
     if font is not None:
         FontEditorSpaceStationController(font.defaultLayer)
     else:
         NSBeep()
Beispiel #14
0
        def __init__(self):
            self.w = Window((500, 400), "InfoLine", minSize=(200, 100))
            hGRPcontrols = 85
            yInfoControl = 20

            self.font = CurrentFont()
            nextG = 5
            self.w.gC1 = TDGroupLine((5, nextG, -5, 0),
                                     separatePairs=False,
                                     selectionCallback=None,
                                     selectionPairCallback=None,
                                     sizeStyle='extrabig',
                                     hasHorizontalScroller=True,
                                     showValues=True,
                                     showMargins=True,
                                     showNames=True)
            nextG += self.w.gC1.heightOfControl + 2

            self.w.gC2 = TDGroupLine((5, nextG, -5, 0),
                                     separatePairs=False,
                                     selectionCallback=None,
                                     selectionPairCallback=None,
                                     sizeStyle='big',
                                     hasHorizontalScroller=True,
                                     showValues=True,
                                     showMargins=True,
                                     showNames=True)
            nextG += self.w.gC2.heightOfControl + 2

            self.w.gC3 = TDGroupLine((5, nextG, -5, 0),
                                     separatePairs=False,
                                     selectionCallback=None,
                                     selectionPairCallback=None,
                                     sizeStyle='regular',
                                     hasHorizontalScroller=True,
                                     showValues=True,
                                     showMargins=True,
                                     showNames=True)
            nextG += self.w.gC3.heightOfControl + 2

            self.w.gC4 = TDGroupLine((5, nextG, -5, 0),
                                     separatePairs=False,
                                     selectionCallback=None,
                                     selectionPairCallback=None,
                                     sizeStyle='small',
                                     hasHorizontalScroller=True,
                                     showValues=True,
                                     showMargins=True,
                                     showNames=True)
            nextG += self.w.gC4.heightOfControl + 2

            self.w.gC5 = TDGroupLine((5, nextG, -5, 0),
                                     separatePairs=False,
                                     selectionCallback=None,
                                     selectionPairCallback=None,
                                     sizeStyle='mini',
                                     hasHorizontalScroller=True,
                                     showValues=True,
                                     showMargins=True,
                                     showNames=True)
            nextG += self.w.gC5.heightOfControl + 2

            self.w.gC6 = TDGroupLine((5, nextG, -5, 0),
                                     separatePairs=False,
                                     selectionCallback=None,
                                     selectionPairCallback=None,
                                     sizeStyle='micro',
                                     hasHorizontalScroller=True,
                                     showValues=True,
                                     showMargins=True,
                                     showNames=True)
            nextG += self.w.gC6.heightOfControl

            self.hashKernDic = TDHashKernDic(self.font)
            l = 'A'
            r = 'O'
            self.w.open()

            self.w.gC1.setFont(self.font, self.hashKernDic)
            self.w.gC1.setPair((l, r), direction='R')
            self.w.gC2.setFont(self.font, self.hashKernDic)
            self.w.gC2.setPair((l, r), direction='R')
            self.w.gC3.setFont(self.font, self.hashKernDic)
            self.w.gC3.setPair((l, r), direction='R')
            self.w.gC4.setFont(self.font, self.hashKernDic)
            self.w.gC4.setPair((l, r), direction='R')
            self.w.gC5.setFont(self.font, self.hashKernDic)
            self.w.gC5.setPair((l, r), direction='R')
            self.w.gC6.setFont(self.font, self.hashKernDic)
            self.w.gC6.setPair((l, r), direction='R')
Beispiel #15
0
        def __init__(self):

            self.w = Window((995, 600),
                            "KernGroups",
                            minSize=(995, 400),
                            maxSize=(995, 2500))
            self.groupPrefix = ID_KERNING_GROUP
            self.direction = 'L'
            self.font = CurrentFont()
            self.w.cbGroupsList = PopUpButton(
                (-240, 5, -5, 21), {},
                callback=self.cbGroupsListCallback,
                sizeStyle='regular')

            self.w.fontView = TDFontView(
                (5, 15, 580, -50),
                font=self.font,
                groupsChangedCallback=self.groupsChanged,
                groupPrefix=self.groupPrefix)
            self.w.groupsView = TDGroupsCollectionView(
                (590, 0, 405, -0),
                font=CurrentFont(),
                direction=self.direction,
                groupsChangedCallback=self.hideGroupedCallback,
                groupPrefix=self.groupPrefix,
                selectionCallback=self.selectionGroup)
            segments = [{
                'width': 54,
                'title': 'Left'
            }, {
                'width': 54,
                'title': 'Right'
            }]
            self.w.btnSwitchLeftRight = SegmentedButton(
                (590, 3, 120, 23),
                segmentDescriptions=segments,
                selectionStyle='one',  # sizeStyle = 'mini', #48
                callback=self.btnSwitchLeftRightCallback,
                sizeStyle='regular')
            # self.modeLeftRight = 0
            self.w.btnSwitchLeftRight.set(0)

            ypos = -90
            self.w.btnMakeGroup = Button((10, ypos, 150, 21),
                                         title='Make Group',
                                         callback=self.makeGroup)
            self.w.btnMakeGroups = Button((10, ypos + 25, 150, 21),
                                          title='Make Groups',
                                          callback=self.makeGroups)

            # self.w.btnFixMarginsGlobal = Button((420, ypos, 150, 21), title = 'Fix Margins', callback = self.fixMarginsGlobal)
            # ypos += 25
            self.w.btnDeleteGroup = Button((420, ypos, 150, 21),
                                           title='Delete Group',
                                           callback=self.deleteGroup)

            self.w.btnRefresh = Button((420, ypos + 25, 150, 21),
                                       title='Refresh',
                                       callback=self.refreshCallback)
            self.w.chbHideGrouped = CheckBox((10, -30, 150, 21),
                                             title='Hide grouped',
                                             value=True,
                                             callback=self.hideGroupedCallback)
            self.w.cbGroupsList.setItems(self.w.groupsView.groupsList)
            self.w.bind('close', self.windowCloseCallback)
            self.w.open()
Beispiel #16
0
        return int(name.split('_')[0], 16)

    def add_tags(self):
        if self.is_double and (self.char == 'ㄲ' or self.char == 'ㄸ'):
            self._separate_contours()
        for point, attr in self.points_attr.items():
            attr.add_attr('char', self.char_tag)
            attr.add_attr('formType', self.form_type)
            if self.is_double and attr.get_attr('double') is None:
                sound = attr.get_attr('sound') center_x = _calc_center(point)[0]
                if sound == 'final':
                    if center_x < 311:
                        attr.add_attr('double', 'left')
                    else:
                        attr.add_attr('double', 'right')


def _calc_center(point):
    box = point.contour.box
    return (box[0] + box[2]) / 2, (box[1] + box[3]) / 2


if __name__ == "__main__":
    def add_tags(glyph):
        YullyeoTagger(glyph).add_tags()

    def tag_cond(glyph):
        return not glyph.name.startswith("uni")

    iterfont.glyph_generator(CurrentFont(), add_tags, add_tags=tag_cond)
Beispiel #17
0
 def doubleClickCallback(self, sender):
     glist = []
     for gindex in self.groupView.getSelection():
         glist.append(self.groupView[gindex].name)
     w = OpenSpaceCenter(CurrentFont())
     w.set(glist)
Beispiel #18
0
 def doubleClickCallback(self, sender):
     w = OpenSpaceCenter(CurrentFont())
     w.set(self.getSelectedGlyphs())
Beispiel #19
0
 def btnApplyCallback(self, info):
     font = CurrentFont()
     charsetName = self.w.cbCharsetsList.get()
     font.lib['public.glyphOrder'] = getCharacterSets()[charsetName]
     font.glyphOrder = font.lib['public.glyphOrder']
     print('CharacterSet switched to', charsetName)
import rbWindow.editWindow as ew
from rbWindow.ExtensionSetting.extensionValue import *
from jsonConverter.makeJsonFile import *
from testCode.initialization import *
from parseSyllable.configVersionFinal import *
from fontParts.world import CurrentFont, OpenFont
from mojo.UI import *

testPath, testFile = launchFontTool()
if testPath is None:
    quit()

print("testPath(launchFontTool) = ", testPath)
configPreset = ConfigExtensionSetting(DefaultKey)
configPreset.checkLangauge()
configPreset.registerSettings()

groupDict = None
# launchFontTool() 리턴 값과 같다면 지워도 무방할듯...? 일단 안지움
testFile = OpenFont(testPath, showInterface=False)

FileNameList = StartProgram(testPath, testFile, CurrentFont())

setExtensionDefault(DefaultKey + ".font", CurrentFont())
setExtensionDefault(DefaultKey + ".jsonFileName1", FileNameList[0])
setExtensionDefault(DefaultKey + ".jsonFileName2", FileNameList[1])
setExtensionDefault(DefaultKey + ".testPath", testPath)
KoreanCheck = getExtensionDefault(DefaultKey + ".korean")

menuWindow = ew.EditGroupMenu(groupDict, FileNameList[0], FileNameList[1])
fontWindowObserver()
""" This is example of adding sound attribute at points using by Yullyeo font data. 

Last modified date: 2019/09/11

Created by Seongju Woo.
"""
from fwig.attributing import sound
from fontParts.world import CurrentFont

class YullyeoSound(sound.Sound):
    def __init__(self, glyph):
        super().__init__(glyph)

    def calculate_sound(self):
        glyph_name = self.glyph.name
        sound_dict = {'C': 0, 'V': 1, 'F': 2}
        if glyph_name.endswith(tuple(sound_dict.keys())):
            return sound_dict[glyph_name[-1]]
        else:
            return -1


if __name__ == "__main__":
    font = CurrentFont()
    for o in font.glyphOrder:
        glyph = font.getGlyph(o)
        if glyph.name.find('uni') == -1:
            YullyeoSound(glyph).add_sound_attr()
def _is_inside_point(glyph, point):
    for contour in glyph.contours:
        if contour.pointInside(point.position):
            if contour == point.contour:
                continue
            return True
    return False

def add_elem_attr(glyph):
    """ Adds elem attribute to RGlyph object. """
    for contour in glyph.contours:
        is_stem = True
        for point in contour.points:
            if point.type == 'offcurve':
                continue
            if _is_inside_point(glyph, point):
                is_stem = False
                break
        if is_stem:
            at.add_attr(contour.points[0], 'elem', 'stem')
        else:
            at.add_attr(contour.points[0], 'elem', 'branch')

def need_elem(glyph):
    """ Finds RGlyph object that needs elem attribute. """
    return not glyph.name.startswith('uni') and glyph.name.endswith('V')

if __name__ == '__main__':
    iterfont.glyph_generator(CurrentFont(), add_elem_attr, add_elem_attr=need_elem)
from fwig.attributing.stroke import add_stroke_attr
from fwig.tools import iterfont
from fontParts.world import CurrentFont


def need_stroke(glyph):
    return not glyph.name.startswith('uni')


if __name__ == '__main__':
    iterfont.glyph_generator(CurrentFont(),
                             add_stroke_attr,
                             add_stroke_attr=need_stroke)