-
Notifications
You must be signed in to change notification settings - Fork 4
/
helper.py
106 lines (96 loc) · 3.1 KB
/
helper.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
import os
import os.path as p
import shutil
import fontforge
import subprocess
import os
import sys
here = p.dirname(p.abspath(__file__))
sys.path.insert(0, p.join(p.dirname(here), 'shutilwhich-cwdpatch'))
from shutilwhich_cwdpatch import which
def rename_font(input, save_as, fontname=None, familyname=None, fullname=None,
sfnt_ref=None, reps=(), clean_up=False, mono=False, remove=(), spaces=()):
"""
Parameters
----------
input : str
Path to font to rename.
fontname, familyname, fullname : str, str, str
Font name parameters.
save_as : str
Save file path.
sfnt_ref : str
path to reference font with right SFNT section
reps : tuple(tuple)
replacements for SFNT section like: (('Roboto', 'Open'), ('STIX', 'STYX'))
mono : bool
set isFixedPitch flag to 1 and OS/2 PANOSE Proportion to Monospaced
remove : iterable
list of characters to delete form a font
spaces : iterable
list of characters to copy whitespace (U+0020) into
"""
def _rep(obj):
if isinstance(obj, str):
for pair in reps:
obj = obj.replace(pair[0], pair[1])
return obj
elif isinstance(obj, tuple):
t = tuple(_rep(o) for o in obj)
if t[1] == 'PostScriptName':
t = tuple([t[0], t[1], t[2].replace(' ', '')] + list(t[3:]))
return t
else:
raise RuntimeError('Tried to replace something that is not tuple/str superposition.')
shutil.copy(input, save_as)
if sfnt_ref is not None:
ref_font = fontforge.open(sfnt_ref)
sfnt_names = _rep(ref_font.sfnt_names)
ref_font.close()
else:
sfnt_names = ()
renamed = fontforge.open(save_as)
renamed.sfnt_names = sfnt_names
if fontname is not None:
renamed.fontname = fontname
if familyname is not None:
renamed.familyname = familyname
if fullname is not None:
renamed.fullname = fullname
if mono:
lst = list(renamed.os2_panose)
lst[3] = 9
renamed.os2_panose = tuple(lst)
if remove:
for c in remove:
renamed.selection[ord(c)] = True
for i in renamed.selection.byGlyphs:
renamed.removeGlyph(i)
if spaces:
renamed.selection.select(ord(' '))
renamed.copy()
renamed.selection.none()
for c in spaces:
renamed.selection.select(ord(c))
renamed.paste()
renamed.selection.none()
if save_as[-4:] == '.sfd':
renamed.save(save_as)
else:
renamed.generate(save_as)
if clean_up:
try:
os.remove(input)
except:
pass
renamed.close()
if mono:
if os.name != 'nt':
pyexe = which('python3')
if not pyexe:
pyexe = which('python')
else:
pyexe = which('python')
if not pyexe:
raise RuntimeError("python executable wasn't found")
print(subprocess.check_output([pyexe, p.join(here, 'setisFixedPitch-fonttools.py'), save_as]))