summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/doc/latex/thuthesis/zhfonts.py
blob: 5ecbd31b9a6d397c0c56e5064cdb054173b9c5b7 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This script can help to choose Chinse fonts found by `fc-list`, which will be
used in thuthesis.

This script prefers the font name in ASCII to the one containing Unicode
character, in order to avoid the problem with 'Adobe 宋体 Std L'.

This script should work with Python 2.6, 2.7 and Python 3.2, providing that your
locale is utf-8. Please report issues if you find.
"""

from __future__ import print_function
from __future__ import unicode_literals

try:
    from subprocess import check_output
except ImportError: # python 2.6 has no check_output
    from subprocess import Popen, PIPE
    def check_output(cmdline):
        return Popen(cmdline, stdout=PIPE).communicate()[0]

# Py3K renames raw_input to input.
try:
    input = raw_input
except:
    pass

import re

# The return value is of type byte string (in py3k).
zh_fonts_str = check_output(['fc-list', '-f', '%{family}\n', ':lang=zh'])
all_fonts_str = check_output(['fc-list', '-f', '%{family}\n'])
if not zh_fonts_str:
    print('No Chinese font exists! Leaving...')
    exit(1)

# strip out ':style=BLABLA' stuff
zh_fonts_list = sorted(set([x.split(b':')[0] for x in zh_fonts_str.splitlines()]))
all_fonts_list = sorted(set([x.split(b':')[0] for x in all_fonts_str.splitlines()]))

# Convert to unicode string, assuming utf-8 encoding of byte string.
# Thus following variables are all unicode string.
zh_fonts_list = [x.decode('utf-8') for x in zh_fonts_list]
all_fonts_list = [x.decode('utf-8') for x in all_fonts_list]

final_fonts = {'songti': {'name': '宋体',
                          'candidates': [],
                          'keyword': '宋|Ming',
                          'font': ''},
               'heiti': {'name': '黑体',
                         'candidates': [],
                         'keyword': '黑|Hei|Sans|Gothic',
                         'font': ''},
               'kaiti': {'name': '楷体',
                         'candidates': [],
                         'keyword': '楷|Kai',
                         'font': ''},
               'fangsong': {'name': '仿宋',
                            'candidates': [],
                            'keyword': '仿宋|Fang',
                            'font': ''},
               'lishu': {'name': '隶书',
                         'candidates': [],
                         'keyword': '隶|Li',
                         'font': ''},
               'youyuan': {'name': '幼圆',
                           'candidates': [],
                           'keyword': '圆|Yuan',
                           'font': ''}}

for zh_font in zh_fonts_list:
    for key in final_fonts:
        if re.search(final_fonts[key]['keyword'], zh_font, re.IGNORECASE):
            final_fonts[key]['candidates'].append(zh_font)
            break

def select_font(font_list):
    if not font_list:
        if not zh_fonts_list:
            if not all_fonts_list:
                return ''
            else:
                return select_font(all_fonts_list)
        else:
            return select_font(zh_fonts_list)

    print('-' * 60);
    for i, v in enumerate(font_list):
        print('{0:d}.\t{1}'.format(i, v))
    print('-' * 60);
    while True:
        # Note input/raw_input in Python 2.x do not accept unicode string.
        print('选择序号(默认0,z: 所有中文字体中选择,a: 所有字体中选择): ', end='')
        n_str = input()
        if not n_str:
            n = 0
        else:
            if n_str == 'z' or n_str =='Z':
                return select_font(zh_fonts_list)
            elif n_str == 'a' or n_str == 'A':
                return select_font(all_fonts_list)
            else:
                try:
                    n = int(n_str)
                except ValueError:
                    continue
        if 0 <= n < len(font_list):
            break
    ascii_font_name = ''
    for x in font_list[n].split(','):
        try:
            x.encode('ascii')
        except UnicodeEncodeError:
            pass
        else:
            ascii_font_name = x
            break
    if ascii_font_name:
        return ascii_font_name
    else:
        print('ASCII font name not found!')
        print('You might encounter error using this font with XeLaTeX...')
        return font_list[n].split(',')[-1]


print('>> 请选择字体:')
for key in final_fonts:
    print('{0}:'.format(final_fonts[key]['name']))
    final_fonts[key]['font'] = select_font(final_fonts[key]['candidates'])
    print()

if not all((final_fonts['songti']['font'],
            final_fonts['heiti']['font'],
            final_fonts['kaiti']['font'])):
    print('错误:缺少宋体、黑体或楷体字体。')
    exit(2)

print('>> 生成字体文件thufonts.def')
with open('thufonts.def', 'w') as f:
    f.write('% vim: set ft=tex:\n')
    f.write('% This file is auto-generated by zhfonts.py script\n\n')
    f.write('\\ProvidesFile{thufonts.def}\n')

    f.write('\\setCJKmainfont[BoldFont={' + final_fonts['heiti']['font'] + '},ItalicFont={' + final_fonts['kaiti']['font'] + '}]{' + final_fonts['songti']['font'] + '}\n')
    f.write('\\setCJKsansfont{' + final_fonts['heiti']['font'] + '}\n')
    f.write('\\setCJKmonofont{' + final_fonts['kaiti']['font'] + '}\n')

    f.write('\\setCJKfamilyfont{zhsong}{' + final_fonts['songti']['font'] + '}\n')
    f.write('\\setCJKfamilyfont{zhhei}{' + final_fonts['heiti']['font'] + '}\n')
    f.write('\\setCJKfamilyfont{zhkai}{' + final_fonts['kaiti']['font'] + '}\n')
    if final_fonts['fangsong']['font']:
        f.write('\\setCJKfamilyfont{zhfs}{' + final_fonts['fangsong']['font'] + '}\n')
    else:
        print('>>> 缺少仿宋,宋体代替')
        f.write('\\setCJKfamilyfont{zhfs}{' + final_fonts['songti']['font'] + '}\n')
    if final_fonts['lishu']['font']:
        f.write('\\setCJKfamilyfont{zhli}{' + final_fonts['lishu']['font'] + '}\n')
    else:
        print('>>> 缺少隶书,宋体代替')
        f.write('\\setCJKfamilyfont{zhli}{' + final_fonts['songti']['font'] + '}\n')
    if final_fonts['youyuan']['font']:
        f.write('\\setCJKfamilyfont{zhyou}{' + final_fonts['youyuan']['font'] + '}\n')
    else:
        print('>>> 缺少幼圆,宋体代替')
        f.write('\\setCJKfamilyfont{zhyou}{' + final_fonts['songti']['font'] + '}\n')
    f.write('''
\\newcommand*{\\songti}{\\CJKfamily{zhsong}}
\\newcommand*{\\heiti}{\\CJKfamily{zhhei}}
\\newcommand*{\\kaishu}{\\CJKfamily{zhkai}}
\\newcommand*{\\fangsong}{\\CJKfamily{zhfs}}
\\newcommand*{\\lishu}{\\CJKfamily{zhli}}
\\newcommand*{\\youyuan}{\\CJKfamily{zhyou}}
''')

print('>> 替换shuji.tex中的仿宋字体')
import fileinput
for line in fileinput.input('shuji.tex', inplace=True):
    line = line.decode('utf-8')
    if line.startswith('  \setCJKfamilyfont{zhfs}[RawFeature={vertical:}]'):
        line = '  \setCJKfamilyfont{zhfs}[RawFeature={vertical:}]{' + final_fonts['fangsong']['font'] + '}\n'
    print(line.encode('utf-8'), end='')

print('>> 中文字体处理结束。')