| 1 |
import fontforge, locale, re, math |
| 2 |
|
| 3 |
指令处理函数 |
| 4 |
|
| 5 |
def multiply_matrices(m1, m2): |
| 6 |
""" FontForge2D仿射变换,二个矩阵乘法 """ |
| 7 |
a1, b1, c1, d1, x1, y1 = m1 |
| 8 |
a2, b2, c2, d2, x2, y2 = m2 |
| 9 |
return ( |
| 10 |
a1 * a2 + b1 * c2, a1 * b2 + b1 * d2, |
| 11 |
c1 * a2 + d1 * c2, c1 * b2 + d1 * d2, |
| 12 |
x1 * a2 + y1 * c2 + x2, x1 * b2 + y1 * d2 + y2 |
| 13 |
) |
| 14 |
|
| 15 |
def parse_and_apply_transform(glyph, command_str): |
| 16 |
try: |
| 17 |
定四极 |
| 18 |
bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax = glyph.boundingBox() |
| 19 |
if bbox_xmin == bbox_ymin == bbox_xmax == bbox_ymax == 0 and not glyph.layers: return False |
| 20 |
|
| 21 |
orig_w, orig_h = glyph.width, glyph.vwidth |
| 22 |
|
| 23 |
本规范 |
| 24 |
cmd_clean = re.sub(r'\s*([\+\-\*\/])\s*', r'\1', command_str.lower()) |
| 25 |
|
| 26 |
令拆分 |
| 27 |
steps = [] |
| 28 |
for cmd, val_str in re.findall(r'([a-z]+)\s*([0-9\+\-\*\/\.\%(\)]*)', cmd_clean): |
| 29 |
自动支持 % 百分比换算) |
| 30 |
v_clean = re.sub(r'[^0-9\+\-\*\/\.\(\)]', '', val_str.replace('%', '/100.0')) if val_str else '0.0' |
| 31 |
val = float(eval(v_clean)) if v_clean else 0.0 |
| 32 |
|
| 33 |
项等值 |
| 34 |
axis_map = { |
| 35 |
'xy': [('x', val), ('y', val)], 'yx': [('x', val), ('y', val)], |
| 36 |
'zt': [('z', val), ('t', val)], 'tz': [('z', val), ('t', val)], |
| 37 |
'hw': [('h', val), ('w', val)], 'wh': [('w', val), ('h', val)] |
| 38 |
} |
| 39 |
steps.extend(axis_map.get(cmd, [(cmd, val)])) |
| 40 |
|
| 41 |
变换 |
| 42 |
final_matrix = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0) |
| 43 |
c_xmin, c_ymin, c_xmax, c_ymax = bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax |
| 44 |
|
| 45 |
for cmd, val in steps: |
| 46 |
cx, cy = (c_xmin + c_xmax) / 2.0, (c_ymin + c_ymax) / 2.0 |
| 47 |
|
| 48 |
计算矩阵 |
| 49 |
rad = math.radians(-val if cmd == 'r' else val) |
| 50 |
cos_r, sin_r = math.cos(rad), math.sin(rad) |
| 51 |
|
| 52 |
matrix_map = { |
| 53 |
'x': (1.0, 0.0, 0.0, 1.0, val, 0.0), |
| 54 |
'y': (1.0, 0.0, 0.0, 1.0, 0.0, val), |
| 55 |
'z': (1.0, 0.0, 0.0, 1.0, (c_xmin + val) - cx, 0.0), |
| 56 |
't': (1.0, 0.0, 0.0, 1.0, 0.0, (c_ymin + val) - cy), |
| 57 |
'r': (cos_r, sin_r, -sin_r, cos_r, 0.0, 0.0), |
| 58 |
'l': (cos_r, sin_r, -sin_r, cos_r, 0.0, 0.0), |
| 59 |
'w': (val, 0.0, 0.0, 1.0, 0.0, 0.0), |
| 60 |
'h': (1.0, 0.0, 0.0, val, 0.0, 0.0), |
| 61 |
'fh': (-1.0, 0.0, 0.0, 1.0, 0.0, 0.0), |
| 62 |
'fv': (1.0, 0.0, 0.0, -1.0, 0.0, 0.0) |
| 63 |
} |
| 64 |
if cmd not in matrix_map: continue |
| 65 |
m_raw = matrix_map[cmd] |
| 66 |
|
| 67 |
接结果,其他功能需在元位变换还元 |
| 68 |
m_step = m_raw if cmd in ['x', 'y', 'z', 't'] else multiply_matrices(multiply_matrices((1.0, 0.0, 0.0, 1.0, -cx, -cy), m_raw), (1.0, 0.0, 0.0, 1.0, cx, cy)) |
| 69 |
final_matrix = multiply_matrices(final_matrix, m_step) |
| 70 |
|
| 71 |
当前边界 |
| 72 |
dx, dy = m_step[4], m_step[5] |
| 73 |
sw = abs(m_raw[0]) if cmd in ['w', 'fh'] else 1.0 |
| 74 |
sh = abs(m_raw[3]) if cmd in ['h', 'fv'] else 1.0 |
| 75 |
|
| 76 |
半,当前四极 |
| 77 |
w_h, h_h = (c_xmax - c_xmin) * sw / 2.0, (c_ymax - c_ymin) * sh / 2.0 |
| 78 |
c_xmin, c_xmax = (cx + dx) - w_h, (cx + dx) + w_h |
| 79 |
c_ymin, c_ymax = (cy + dy) - h_h, (cy + dy) + h_h |
| 80 |
|
| 81 |
原宽高 |
| 82 |
glyph.transform(final_matrix) |
| 83 |
glyph.width, glyph.vwidth = orig_w, orig_h |
| 84 |
glyph.changed() |
| 85 |
return True |
| 86 |
except: |
| 87 |
return False |
| 88 |
|
| 89 |
居周处理函数 |
| 90 |
|
| 91 |
def process_glyph_alignment(font_obj, glyph_name, align_type="center_both"): |
| 92 |
try: |
| 93 |
glyph, ascent = font_obj[glyph_name], font_obj.ascent |
| 94 |
g_width = glyph.width |
| 95 |
g_height = glyph.vwidth if glyph.vwidth > 0 else (ascent + font_obj.descent) |
| 96 |
|
| 97 |
定四极 |
| 98 |
xmin, ymin, xmax, ymax = glyph.boundingBox() |
| 99 |
if xmin == ymin == xmax == ymax == 0 and not glyph.layers: |
| 100 |
return False |
| 101 |
|
| 102 |
中央,中央先于无方 |
| 103 |
x_left = "left" in align_type |
| 104 |
x_right = "right" in align_type |
| 105 |
x_center = "center" in align_type or "both" in align_type or "horizontal" in align_type |
| 106 |
|
| 107 |
位,横向儴位 |
| 108 |
tgt_x, cur_x = (0.0, 0.0) 认不位移 |
| 109 |
if x_left: tgt_x, cur_x = (0.0, xmin) |
| 110 |
elif x_right: tgt_x, cur_x = (g_width, xmax) |
| 111 |
elif x_center: tgt_x, cur_x = (g_width / 2.0, (xmin + xmax) / 2.0) |
| 112 |
|
| 113 |
中央,中央先于无方 |
| 114 |
y_top = "top" in align_type |
| 115 |
y_bottom = "bottom" in align_type |
| 116 |
y_center = "center" in align_type or "both" in align_type or "vertical" in align_type |
| 117 |
|
| 118 |
位,从向儴位 |
| 119 |
tgt_y, cur_y = (0.0, 0.0) 认不位移 |
| 120 |
if y_top: tgt_y, cur_y = (ascent, ymax) |
| 121 |
elif y_bottom: tgt_y, cur_y = (ascent - g_height, ymin) |
| 122 |
elif y_center: tgt_y, cur_y = (ascent - g_height / 2.0, (ymin + ymax) / 2.0) |
| 123 |
|
| 124 |
形变换 |
| 125 |
glyph.transform((1.0, 0.0, 0.0, 1.0, tgt_x - cur_x, tgt_y - cur_y)) |
| 126 |
glyph.width, glyph.vwidth = g_width, g_height |
| 127 |
glyph.changed() |
| 128 |
return True |
| 129 |
except: |
| 130 |
return False |
| 131 |
|
| 132 |
字形,两者窗口所传 |
| 133 |
|
| 134 |
def run_alignment(passed_obj, align_type): |
| 135 |
字体对象 |
| 136 |
font_obj = passed_obj.font if hasattr(passed_obj, 'font') else fontforge.activeFont() |
| 137 |
if not font_obj: return |
| 138 |
|
| 139 |
字形列表 |
| 140 |
glyph_names = [passed_obj.glyphname] if hasattr(passed_obj, 'glyphname') else [g.glyphname for g in font_obj.selection.byGlyphs] |
| 141 |
|
| 142 |
指令弹窗 |
| 143 |
if align_type == "custom_transform": |
| 144 |
数有限 |
| 145 |
prompt_zh = ( |
| 146 |
"【横从|纬经|宽高|顺逆|反倒】:\n" |
| 147 |
" x,y(xy) | z,t(zt) | w,h(wh) | r,l | fh,fv" |
| 148 |
) |
| 149 |
写(Loc/Glo/Scl/Rot/Flp) |
| 150 |
prompt_en = ( |
| 151 |
"【Loc|Glo|Scl|Rot|Flp】:\n" |
| 152 |
" x,y(xy) | z,t(zt) | w,h(wh) | r,l | fh,fv" |
| 153 |
) |
| 154 |
原生输入文框 |
| 155 |
prompt = prompt_zh if is_zh else prompt_en |
| 156 |
title = "自由变换" if is_zh else "Custom Transform" |
| 157 |
user_input = fontforge.askString(title, prompt, "") |
| 158 |
|
| 159 |
if user_input: |
| 160 |
for name in glyph_names: |
| 161 |
parse_and_apply_transform(font_obj[name], user_input) |
| 162 |
else: |
| 163 |
令归置位 |
| 164 |
for name in glyph_names: |
| 165 |
process_glyph_alignment(font_obj, name, align_type) |
| 166 |
|
| 167 |
单注册】 |
| 168 |
|
| 169 |
系统语言 |
| 170 |
try: |
| 171 |
lang_code, _ = locale.getdefaultlocale() |
| 172 |
is_zh = bool(lang_code and lang_code.startswith("zh")) |
| 173 |
except: |
| 174 |
is_zh = False |
| 175 |
|
| 176 |
menu_tools = "字形置位" if is_zh else "Glyph Alignment" |
| 177 |
|
| 178 |
五方向 |
| 179 |
directions = [ |
| 180 |
("center_both", "居中正", "Center Both"), ("center_vertical", "居中从", "Center Vertical"), |
| 181 |
("center_horizontal", "居中横", "Center Horizontal"), ("center_top", "居中上", "Center Top"), |
| 182 |
("center_bottom", "居中下", "Center Bottom"), ("center_left", "居中左", "Center Left"), |
| 183 |
("center_right", "居中右", "Center Right"), ("top_left", "居左上", "Top Left"), |
| 184 |
("bottom_left", "居左下", "Bottom Left"), ("top_right", "居右上", "Top Right"), |
| 185 |
("bottom_right", "居右下", "Bottom Right"), ("top", "居上", "Top"), |
| 186 |
("bottom", "居下", "Bottom"), ("left", "居左", "Left"), |
| 187 |
("right", "居右", "Right") |
| 188 |
] |
| 189 |
|
| 190 |
体窗口、字形窗口 |
| 191 |
for dtype, zh, en in directions: |
| 192 |
fontforge.registerMenuItem(lambda m, p, dt=dtype: run_alignment(p, dt), None, None, "Font", None, menu_tools, zh if is_zh else en) |
| 193 |
fontforge.registerMenuItem(lambda m, p, dt=dtype: run_alignment(p, dt), None, None, "Char", None, menu_tools, zh if is_zh else en) |
| 194 |
的【自定义命令输入】菜单项 |
| 195 |
custom_zh, custom_en = "变换指令", "Transformation Command" |
| 196 |
fontforge.registerMenuItem(lambda m, p: run_alignment(p, "custom_transform"), None, None, "Font", None, menu_tools, custom_zh if is_zh else custom_en) |
| 197 |
fontforge.registerMenuItem(lambda m, p: run_alignment(p, "custom_transform"), None, None, "Char", None, menu_tools, custom_zh if is_zh else custom_en) |
| 198 |
|
| 199 |
加键位】 |
| 200 |
|
| 201 |
import os, sys |
| 202 |
|
| 203 |
运行环境 |
| 204 |
is_win = sys.platform.startswith("win") |
| 205 |
|
| 206 |
本,绝对路径 |
| 207 |
script_path = os.path.abspath(__file__) |
| 208 |
script_dir = os.path.dirname(script_path) |
| 209 |
|
| 210 |
格式,用于特征匹配 |
| 211 |
norm_dir = script_dir.replace("\\", "/").lower() |
| 212 |
|
| 213 |
版,路径所在 |
| 214 |
is_shared_env = "share/fontforge/python" in norm_dir or "share/fontforge" in norm_dir |
| 215 |
|
| 216 |
if is_shared_env: |
| 217 |
本,是免安装 |
| 218 |
idx = norm_dir.find("share/fontforge") |
| 219 |
base_dir = script_dir[:idx] if idx != -1 else os.path.dirname(os.path.dirname(script_dir)) |
| 220 |
hotkeys_path = os.path.join(base_dir, "share", "fontforge", "hotkeys", "default") |
| 221 |
os.makedirs(os.path.dirname(hotkeys_path), exist_ok=True) |
| 222 |
else: |
| 223 |
本,非免安装 |
| 224 |
appdata = os.environ.get("APPDATA") if is_win else os.path.expanduser("~") |
| 225 |
fontforge_dir = os.path.join(appdata, "FontForge" if is_win else ".FontForge") |
| 226 |
hotkeys_path = os.path.join(fontforge_dir, "hotkeys" if is_win else "shortcuts") |
| 227 |
os.makedirs(fontforge_dir, exist_ok=True) |
| 228 |
|
| 229 |
前系统语言环境 |
| 230 |
try: |
| 231 |
sys_lang, _ = locale.getdefaultlocale() |
| 232 |
except Exception: |
| 233 |
sys_lang = "en" |
| 234 |
is_zh_sys = bool(sys_lang and sys_lang.startswith("zh")) |
| 235 |
|
| 236 |
单,路径前缀 |
| 237 |
zh_pfx = ("FontView.Menu.Tools.字形置位.", "CharView.Menu.Tools.字形置位.") |
| 238 |
en_pfx = ("FontView.Menu.Tools.Glyph Alignment.", "CharView.Menu.Tools.Glyph Alignment.") |
| 239 |
|
| 240 |
前前缀]以及[冲突前缀] |
| 241 |
prefix, opp_prefix = (zh_pfx, en_pfx) if is_zh_sys else (en_pfx, zh_pfx) |
| 242 |
|
| 243 |
示、键位文本 |
| 244 |
if is_zh_sys: |
| 245 |
gui_title = "字形置位提示" |
| 246 |
err_r_title, err_r_msg = "读取键位失败", "读取不了原本配置文件,原因:\n" |
| 247 |
err_w_title, err_w_msg = "写入键位失败", "键位无法写入配置文件,原因:\n" |
| 248 |
no_change_msg = "检测完毕。\n当前系统的所有键位已正确配置,未做任何修改。" |
| 249 |
succ_msg = lambda a, r: f"完成键位配置!\n\n 修改目标: {hotkeys_path}\n\n 清理外文键位:{r} 项。\n 更新补全键位:{a} 项。\n\n重启软件之后,键位自动激活。" |
| 250 |
|
| 251 |
suffixes = ["居中正: Ctrl+ᄉ", "居中从: Ctrl+ᆴ", "居中横: Ctrl+ᄚ", "居中上: Ctrl+ᄌ", "居中下: Ctrl+ᄇ", "居中左: Ctrl+ᄡ", "居中右: Ctrl+ᄊ", "居左上: Ctrl+ᄋ", "居左下: Ctrl+ᄆ", "居右上: Ctrl+ᄍ", "居右下: Ctrl+ᄈ", "居上: Ctrl+ᆳ", "居下: Ctrl+ᆱ", "居左: Ctrl+ᆵ", "居右: Ctrl+ᆰ", "变换指令:ᄚ"] |
| 252 |
else: |
| 253 |
gui_title = "Glyph Alignment Notice" |
| 254 |
err_r_title, err_r_msg = "Failed to Read Hotkeys", "Cannot read the shortcut configuration file. Reason:\n" |
| 255 |
err_w_title, err_w_msg = "Failed to Write Hotkeys", "Cannot write hotkeys to the configuration file. Reason:\n" |
| 256 |
no_change_msg = "Scan completed.\nGlyph Alignment menu options already exist and match current language. No changes were made." |
| 257 |
succ_msg = lambda a, r: f"Hotkey patch completed!\n\n Target: {hotkeys_path}\n\n Successfully removed conflicting language keys: {r}.\n Successfully added/updated: {a} shortcut(s).\n\nPlease restart FontForge to activate the numpad hotkeys!" |
| 258 |
|
| 259 |
suffixes = ["Center in Height & Width: Ctrl+ᄉ", "Center in Height: Ctrl+ᆴ", "Center in Width: Ctrl+ᄚ", "Center Top: Ctrl+ᄌ", "Center Bottom: Ctrl+ᄇ", "Center Left: Ctrl+ᄡ", "Center Right: Ctrl+ᄊ", "Top Left: Ctrl+ᄋ", "Bottom Left: Ctrl+ᄆ", "Top Right: Ctrl+ᄍ", "Bottom Right: Ctrl+ᄈ", "Top: Ctrl+ᆳ", "Bottom: Ctrl+ᆱ", "Left: Ctrl+ᆵ", "Right: Ctrl+ᆰ", "Transformation Command:ᄚ"] |
| 260 |
|
| 261 |
卅行键位 |
| 262 |
raw_hotkeys = [f"{p}{s}" for p in prefix for s in suffixes] |
| 263 |
|
| 264 |
滤冲突语言键位,保留用户自定义键 |
| 265 |
clean_file_lines, existing_paths, removed_count = [], set(), 0 |
| 266 |
lines = [] |
| 267 |
|
| 268 |
配置,预防文件尚无 |
| 269 |
if os.path.exists(hotkeys_path): |
| 270 |
try: |
| 271 |
with open(hotkeys_path, "r", encoding="utf-8") as f: |
| 272 |
lines = f.readlines() |
| 273 |
except Exception as e: |
| 274 |
fontforge.postError(err_r_title, f"{err_r_msg}{e}") |
| 275 |
|
| 276 |
突语言,保留用户自定义键 |
| 277 |
for line in lines: |
| 278 |
is_valid = line.strip() and not line.strip().startswith("#") and ":" in line |
| 279 |
menu_path = line.split(":")[0].strip() if is_valid else "" |
| 280 |
|
| 281 |
冲突键位 |
| 282 |
if menu_path.startswith(opp_prefix): |
| 283 |
removed_count += 1 |
| 284 |
continue |
| 285 |
应存键位 |
| 286 |
if menu_path.startswith(prefix): |
| 287 |
existing_paths.add(menu_path) |
| 288 |
|
| 289 |
clean_file_lines.append(line) |
| 290 |
|
| 291 |
补缺,合并覆盖写入 |
| 292 |
lines_to_append = [line for line in raw_hotkeys if line.split(":")[0].strip() not in existing_paths] |
| 293 |
|
| 294 |
备,无需修改 |
| 295 |
if removed_count == 0 and not lines_to_append: |
| 296 |
fontforge.logWarning(no_change_msg) |
| 297 |
else: |
| 298 |
合并写入文件 |
| 299 |
try: |
| 300 |
file_content = "".join(clean_file_lines).rstrip() + ("\n\n" + "\n".join(lines_to_append) + "\n" if lines_to_append else "\n") |
| 301 |
with open(hotkeys_path, "w", encoding="utf-8") as f: |
| 302 |
f.write(file_content) |
| 303 |
fontforge.postNotice(gui_title, succ_msg(len(lines_to_append), removed_count)) |
| 304 |
except Exception as e: |
| 305 |
fontforge.postError(err_w_title, f"{err_w_msg}{e}") |
| 306 |
|