Debian Codegraph @

scripts/build_zx_fonts.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 from fontTools.ttLib import TTFont
5 import os
6
7 def create_renamed_font(input_path, output_path, old_base_name, new_base_name_internal, new_base_name_file):
8 """
9 Create a new font with renamed font family from an existing font
10
11 Parameters:
12 input_path (str): Path to the input font file
13 output_path (str): Path to the output font file
14 old_base_name (str): Original font name base
15 new_base_name_internal (str): New internal font name base (with spaces)
16 new_base_name_file (str): New file name base (without spaces)
17 """
18 # Open the original font
19 font = TTFont(input_path)
20
21 # Process the name table
22 for name_record in font['name'].names:
23 decoded_name = name_record.toUnicode()
24
25 if old_base_name in decoded_name:
26 # For nameID 3 (Unique identifier) and nameID 6 (PostScript name), use new_base_name_file (without spaces)
27 if name_record.nameID in (3, 6):
28 new_string = decoded_name.replace(old_base_name, new_base_name_file)
29 # For all other nameIDs, use new_base_name_internal (with spaces)
30 else:
31 new_string = decoded_name.replace(old_base_name, new_base_name_internal)
32
33 name_record.string = new_string.encode(encoding=name_record.getEncoding())
34
35 # Process CFF table if it exists (for .otf fonts)
36 if 'CFF ' in font:
37 try:
38 # Get the CFF table
39 cff_table = font['CFF ']
40
41 # Process the font names in the CFF table
42 if hasattr(cff_table, 'cff'):
43 cff = cff_table.cff
44
45 # Update the fontNames list
46 for i, fontname in enumerate(cff.fontNames):
47 if old_base_name in fontname:
48 cff.fontNames[i] = fontname.replace(old_base_name, new_base_name_file)
49
50 # Process each font in the CFF table
51 for font_name in cff.keys():
52 cff_font = cff[font_name]
53
54 # Update strings in the TopDict
55 if hasattr(cff_font, 'ROS'):
56 # Skip CID-keyed fonts which have different structure
57 continue
58
59 # Update FontName (PostScript name)
60 if hasattr(cff_font, 'FontName') and old_base_name in cff_font.FontName:
61 cff_font.FontName = cff_font.FontName.replace(old_base_name, new_base_name_file)
62
63 # Access and update the Top DICT strings
64 top_dict = cff_font.rawDict
65
66 # Update FullName if it exists
67 if 'FullName' in top_dict and old_base_name in top_dict['FullName']:
68 top_dict['FullName'] = top_dict['FullName'].replace(old_base_name, new_base_name_internal)
69
70 # Update FamilyName if it exists
71 if 'FamilyName' in top_dict and old_base_name in top_dict['FamilyName']:
72 top_dict['FamilyName'] = top_dict['FamilyName'].replace(old_base_name, new_base_name_internal)
73
74 # Debug information
75 print(f"CFF table for {os.path.basename(input_path)}:")
76 if 'FullName' in top_dict:
77 print(f" - FullName: {top_dict['FullName']}")
78 if 'FamilyName' in top_dict:
79 print(f" - FamilyName: {top_dict['FamilyName']}")
80
81 except Exception as e:
82 print(f"Warning: Could not fully process CFF table: {e}")
83 print(f"The font will still be processed, but CFF names might not be updated correctly.")
84
85 # Save the modified font as a new file
86 font.save(output_path)
87
88 # Free memory
89 font.close()
90
91 return output_path
92
93 def process_font_directory(directory_path, old_base_name, new_base_name_internal, new_base_name_file):
94 """
95 Process all font files in a directory
96
97 Parameters:
98 directory_path (str): Path to the directory containing font files
99 old_base_name (str): Original font name base
100 new_base_name_internal (str): New internal font name base (with spaces)
101 new_base_name_file (str): New file name base (without spaces)
102 """
103 # Check if directory exists
104 if not os.path.isdir(directory_path):
105 print(f"Error: Directory '{directory_path}' not found.")
106 return
107
108 # Get all files in the directory
109 all_files = os.listdir(directory_path)
110 font_files = []
111
112 # Filter files matching the pattern
113 for file in all_files:
114 # Select files starting with 0xProto- and ending with .otf or .ttf
115 if file.startswith(f"{old_base_name}-") and (file.endswith(".otf") or file.endswith(".ttf")):
116 font_files.append(os.path.join(directory_path, file))
117
118 # Display search results
119 print(f"Total files in directory: {len(all_files)}")
120 print(f"Detected font files: {len(font_files)}")
121
122 if not font_files:
123 print(f"Warning: No files matching '{old_base_name}-*.(otf|ttf)' pattern found.")
124 # Display files in directory (for debugging)
125 print("\nFiles in directory:")
126 for file in all_files:
127 print(f"- {file}")
128 return
129
130 # Create output directory
131 output_dir = os.path.join(directory_path, "ZxProto")
132 os.makedirs(output_dir, exist_ok=True)
133
134 processed_files = 0
135 failed_files = []
136 otf_files_processed = 0
137 ttf_files_processed = 0
138
139 for input_path in font_files:
140 # Get filename only (no path)
141 filename = os.path.basename(input_path)
142
143 # Create new filename (without spaces)
144 new_filename = filename.replace(old_base_name, new_base_name_file)
145 output_path = os.path.join(output_dir, new_filename)
146
147 # Check if output file exists
148 if os.path.exists(output_path):
149 response = input(f"{output_path} already exists. Overwrite? (y/n): ")
150 if response.lower() != 'y':
151 print(f"Skipping {output_path}.")
152 continue
153
154 # Rename and copy font
155 try:
156 created_file = create_renamed_font(
157 input_path,
158 output_path,
159 old_base_name,
160 new_base_name_internal,
161 new_base_name_file
162 )
163 print(f"Processed: {filename} -> {os.path.basename(created_file)}")
164 processed_files += 1
165
166 # Count by file type
167 if filename.endswith(".otf"):
168 otf_files_processed += 1
169 elif filename.endswith(".ttf"):
170 ttf_files_processed += 1
171
172 except Exception as e:
173 print(f"Error ({filename}): {e}")
174 failed_files.append(filename)
175
176 # Display results
177 print("\nProcessing results:")
178 print(f"- Target files: {len(font_files)}")
179 print(f"- Successfully processed: {processed_files}")
180 print(f" - OTF files: {otf_files_processed}")
181 print(f" - TTF files: {ttf_files_processed}")
182
183 if failed_files:
184 print(f"- Failed: {len(failed_files)}")
185 print("\nFiles that failed processing:")
186 for f in failed_files:
187 print(f"- {f}")
188
189 print(f"\nConverted files have been saved to '{output_dir}' directory.")
190
191 if __name__ == "__main__":
192 font_directory = "fonts"
193 old_name = "0xProto"
194 new_name_internal = "Zx Proto" # Internal font name with spaces
195 new_name_file = "ZxProto" # File name without spaces
196
197 print(f"Processing fonts in '{font_directory}' directory...")
198 print(f"Search pattern: '{old_name}-*.(otf|ttf)'")
199 print(f"Internal font name: '{old_name}' → '{new_name_internal}' (most name records)")
200 print(f"PostScript name & unique ID: '{old_name}' → '{new_name_file}' (nameID 3 and 6)")
201 print(f"CFF table names: Will be updated accordingly (for .otf fonts)")
202 print(f"File name: '{old_name}' → '{new_name_file}'")
203 print("")
204
205 process_font_directory(font_directory, old_name, new_name_internal, new_name_file)
206 print("\nProcessing complete.")