new-fingering-engraver.cc: get 'script-priority from grobs, if set.
[lilypond.git] / python / fontextract.py
blobee9505f37f8eaa7c4c8094d11c538cdfd84f4d10
1 import re
3 import getopt
4 import sys
5 import os
7 dsr_font_regex = re.compile ('%%DocumentSuppliedResources: font (.*)')
8 begin_font_regex = re.compile ('%%BeginFont: (.*)')
9 end_font_regex = re.compile ('%%EndFont')
10 verbose = 0
12 try:
13 import gettext
14 gettext.bindtextdomain ('lilypond', localedir)
15 gettext.textdomain ('lilypond')
16 _ = gettext.gettext
17 except:
18 def _ (s):
19 return s
21 def scan_files (files):
22 file_of_font_dict = {}
23 for f in files:
24 if verbose:
25 sys.stderr.write (_('Scanning %s') % f + '\n')
27 header = open (f, 'r').read ()
28 idx = 0
30 extract_from_this = []
31 while idx < len (header):
32 match = dsr_font_regex.search (header[idx:])
33 if not match:
34 break
35 name = match.group (1)
36 idx += match.end (1)
37 if file_of_font_dict.has_key (name):
38 continue
40 file_of_font_dict[name] = f
42 return file_of_font_dict
44 def get_file_fonts_dict (file_of_font_dict):
45 dict = {}
46 for (n, f) in file_of_font_dict.items ():
47 if not dict.has_key (f):
48 dict[f] = []
50 dict[f].append (n)
52 return dict
54 def extract_fonts_from_file (extract_from_this, font_dict, filename):
55 if extract_from_this:
56 curr_font = []
57 curr_font_name = []
58 in_font = 0
59 for l in open (filename).readlines ():
60 if not in_font and begin_font_regex.match (l):
61 in_font = 1
62 curr_font_name = begin_font_regex.match (l).group (1)
63 curr_font = []
64 elif in_font and end_font_regex.match (l):
65 in_font = 0
67 if curr_font_name in extract_from_this:
68 font_dict[curr_font_name] = ''.join (curr_font)
69 if verbose:
70 sys.stderr.write (_('Extracted %s')
71 % curr_font_name + '\n')
73 extract_from_this.remove (curr_font_name)
74 elif in_font:
75 curr_font.append (l)
76 if not extract_from_this:
77 break
79 if extract_from_this:
80 sys.stderr.write ("Failed to extract %s from %s\n"
81 % (', '.join (extract_from_this), filename))
83 def write_extracted_fonts (output_file_name, font_dict):
84 if verbose:
85 sys.stderr.write( _('Writing fonts to %s') % output_file_name + '\n')
86 output = open (output_file_name, 'w')
87 output.write ('''%!PS-Adobe-3.0
88 %%VMusage: 0 0
89 %%Creator: lilypond-extract-fonts
90 ''')
92 for x in font_dict.keys ():
93 output.write ('%%%%DocumentSuppliedResources: font %s\n' % x)
95 output.write ('''%%EndComments\n''')
97 for (k,v) in font_dict.items ():
98 output.write ('\n%%%%BeginFont: %s\n' % k)
99 output.write (v)
100 output.write ('\n%%EndFont')
103 def extract_fonts (output_file_name, input_files):
104 d = scan_files (input_files)
105 ff = get_file_fonts_dict (d)
107 font_dict = {}
108 for (file, fonts) in ff.items ():
109 extract_fonts_from_file (fonts, font_dict, file)
111 write_extracted_fonts (output_file_name, font_dict)
114 if __name__ == '__main__':
115 extract_fonts ('fonts.ps', sys.argv[1:])