-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminimizeFont.py
217 lines (175 loc) · 5.98 KB
/
minimizeFont.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from io import open
import sys
import os
import collections
import fontforge
# ignore warning
# import warnings
# warnings.filterwarnings("ignore")
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator
from PyQt5.QtWidgets import (QFileDialog, QDialog, QPushButton,
QLineEdit, QLabel, QCheckBox,
QApplication, QVBoxLayout)
useUnichr = True
if not useUnichr:
unichr = str
class askSetting(QDialog):
def __init__(self,
app=None,
parent=None,
items=None):
super(askSetting, self).__init__(parent)
self.app = app
self.items = items
layout = QVBoxLayout()
self.lineedits = collections.OrderedDict()
self.buttons = collections.OrderedDict()
for key in items.keys():
if isinstance(items[key], bool):
self.buttons[key] = QCheckBox(key)
self.buttons[key].setChecked(items[key])
self.buttons[key].setFocusPolicy(Qt.StrongFocus)
layout.addWidget(self.buttons[key])
else:
layout.addWidget(QLabel(key))
self.lineedits[key] = QLineEdit()
if isinstance(items[key], int):
self.lineedits[key].setText(str(items[key]))
# self.lineedits[key].setInputMask("000")
self.lineedits[key].setMaxLength(3)
self.lineedits[key].setValidator(
QIntValidator(1, 999, self))
else:
self.lineedits[key].setText(items[key])
# enable ime input
self.lineedits[key].inputMethodQuery(Qt.ImEnabled)
layout.addWidget(self.lineedits[key])
self.btn = QPushButton('TTF File to Read', self)
self.btn.clicked.connect(lambda: (self.bye(items)))
self.btn.setFocusPolicy(Qt.StrongFocus)
layout.addWidget(self.btn)
self.setLayout(layout)
self.setWindowTitle(' Setting ')
def bye(self, items):
fileName = QFileDialog.getOpenFileName(
self, 'Dialog Title', '~/', initialFilter='*.ttf')
if fileName == (u'', u'*.ttf'):
print("Must Provide an input TTF file.")
sys.exit()
for key in self.buttons.keys():
self.items[key] = self.buttons[key].isChecked()
for key in self.lineedits.keys():
self.items[key] = self.lineedits[key].text()
self.items['getOpenFileName'] = fileName[0]
self.close()
self.app.exit(1)
inFilePrompt = "File to read"
defaultInFile = "minifyGlyphs"
# outFilePrompt = "Minimize TTF File to write"
# defaultOutFile = "out.ttf"
generateGlyphAsEPS = "Generate Glyph As EPS"
generateGlyphAsPNG = "Generate Glyph As PNG"
defaultPNGSize = "PNG Pixel Size"
items = collections.OrderedDict()
items[inFilePrompt] = defaultInFile
# items[outFilePrompt] = defaultOutFile
items[generateGlyphAsEPS] = True
items[generateGlyphAsPNG] = True
items[defaultPNGSize] = 48
app = QApplication(sys.argv)
ask = askSetting(app=app, items=items)
ask.show()
rtnCode = app.exec_()
# If press OK button rtnCode should be 1
if rtnCode != 1:
print('User abort by closing Setting dialog')
sys.exit
# print(items)
ttfFile = fontforge.open(items['getOpenFileName'])
f = open(items[inFilePrompt], 'r', encoding="utf-8")
ttfFile.selection.none()
###
# file contents
# ## start with "##" line will be ignore to read
# 問
# 问
# ie. \w
# ie. word
###
# Pseudo Old FontForge Script
# SelectNone()
# SelectMore(...)
# SelectInvert()
# Clear()
# Generate()
###
count = 0
for line in f:
if line.startswith("##"):
continue
words = line.encode("raw_unicode_escape").split()
# words = line.split()
# print(len(words))
if len(words) == 1:
sys.stdout.write(words[0].decode('unicode_escape'))
count += 1
if count % 25 == 0:
sys.stdout.write("\n")
sys.stdout.flush()
if words[0].startswith(b'\u'):
# print(words[0].decode('unicode_escape'))
ttfFile.selection.select(("more", None), words[0][1:])
elif len(words[0]) == 1:
# print(words[0].decode('unicode_escape'))
ttfFile.selection.select(("more", None), words[0])
ttfFile.selection.invert()
ttfFile.clear()
ttfFile.fontname = ttfFile.fontname + "-SKIM"
ttfFile.familyname = ttfFile.familyname + "-SKIM"
if not os.path.exists("out"):
os.makedirs("out")
ttfFile.generate("out/"+ttfFile.fontname+u".ttf")
print(u'\nGenerated '+ttfFile.fontname+u" as out/"+ttfFile.fontname+u".ttf \n")
ttfFile.selection.invert()
if items[generateGlyphAsEPS]:
if not os.path.exists("out/eps"):
os.makedirs("out/eps")
count = 0
print(u'\nGenerating EPS')
for glyph in ttfFile.selection.byGlyphs:
glyph.export("out/eps/"+unichr(glyph.unicode)+".eps")
sys.stdout.write('.')
sys.stdout.flush()
count += 1
print("\n"+str(count)+" elements export as out/eps/{unicode}.eps")
if items[generateGlyphAsPNG]:
pngSize = items[defaultPNGSize]
if int(pngSize) < 8:
print("PNG Size should at least 8 pixel, set to 8 now.")
pngSize = "8"
if not os.path.exists("out/png"):
os.makedirs("out/png")
count = 0
print(u'\nGenerating PNG @ '+pngSize)
for glyph in ttfFile.selection.byGlyphs:
glyph.export("out/png/"
+ unichr(glyph.unicode)
+ "."
+ pngSize
+ ".png",
int(pngSize),
1)
sys.stdout.write('.')
sys.stdout.flush()
count += 1
print("\n"
+ str(count)
+ " elements export as out/png/{unicode}."
+ pngSize
+ ".png")
if items[generateGlyphAsEPS] or items[generateGlyphAsPNG]:
print(u'\nGenerated '+ttfFile.fontname +
u" as out/"+ttfFile.fontname+u".ttf \n")