]> git.lyx.org Git - lyx.git/blob - development/tools/generate_symbols_images.py
7787e5d2534a4f7923726ff424aa333561e413f8
[lyx.git] / development / tools / generate_symbols_images.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file generate_symbols_images.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Georg Baum
9
10 # Full author contact details are available in file CREDITS
11
12 # This script generates a toolbar image for each missing math symbol
13 # It needs the template document generate_symbols_images.lyx, which must
14 # contain the placeholder formula '$a$' for generating the png image via
15 # preview.sty and dvipng.
16 # The created images are not always optimal, therefore the existing manually
17 # created images should never be replaced by automatically created ones.
18
19
20 import os, re, string, sys, subprocess, tempfile, shutil
21 import Image
22
23 def usage(prog_name):
24     return ("Usage: %s lyxexe outputpath\n" % prog_name)
25
26
27 def error(message):
28     sys.stderr.write(message + '\n')
29     sys.exit(1)
30
31
32 def getlist(lyxexe, lyxfile):
33     """ Call LyX and get a list of symbols from mathed debug output.
34         This way, we can re-use the symbols file parser of LyX, and do not
35         need to reimplement it in python. """
36
37     # The debug is only generated if lyxfile contains a formula
38     cmd = "%s %s -dbg mathed -x lyx-quit" % (lyxexe, lyxfile)
39     proc = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
40     (stdout, stderr) = proc.communicate()
41     regexp = re.compile(r'.*: read symbol \'(\S+)\s+inset:\s+(\S+)')
42     # These insets are more complex than simply symbols, so the images need to
43     # be created manually
44     skipinsets = ['big', 'font', 'lyxblacktext', 'matrix', 'mbox', 'oldfont', \
45                   'ref', 'split', 'space', 'style']
46     symbols = []
47     for line in stderr.split('\n'):
48         m = regexp.match(line)
49         if m:
50             inset = m.group(2)
51             if not inset in skipinsets:
52                 symbols.append(m.group(1))
53     return symbols
54
55
56 def getreplacements(filename):
57     replacements = {}
58     replacements['|'] = 'vert'
59     replacements['/'] = 'slash'
60     replacements['\\'] = 'backslash'
61     replacements['*'] = 'ast'
62     replacements['AA'] = 'textrm_AA'
63     replacements['O'] = 'textrm_O'
64     cppfile = open(filename, 'rt')
65     regexp = re.compile(r'.*"([^"]+)",\s*"([^"]+)"')
66     found = False
67     for line in cppfile.readlines():
68         if found:
69             m = regexp.match(line)
70             if m:
71                 replacements[m.group(1)] = m.group(2)
72             else:
73                 return replacements
74         elif line.find('PngMap sorted_png_map') == 0:
75             found = True
76
77
78 def createimage(name, path, template, lyxexe, tempdir, replacements):
79     """ Create the image file for symbol name in path. """
80
81     if name in replacements.keys():
82         filename = replacements[name]
83     elif name.startswith('lyx'):
84         print 'Skipping ' + name
85         return
86     else:
87         skipchars = ['|', '/', '\\', '*', '!', '?', ':', ';', '^', '<', '>']
88         for i in skipchars:
89             if name.find(i) >= 0:
90                 print 'Skipping ' + name
91                 return
92         filename = name
93     pngname = os.path.join(path, filename + '.png')
94     if os.path.exists(pngname):
95         print 'Skipping ' + name
96         return
97     print 'Generating ' + name
98     lyxname = os.path.join(tempdir, filename)
99     lyxfile = open(lyxname + '.lyx', 'wt')
100     lyxfile.write(template.replace('$a$', '$\\' + name + '$'))
101     lyxfile.close()
102     cmd = "%s %s.lyx -e dvi" % (lyxexe, lyxname)
103     proc = subprocess.Popen(cmd, shell=True)
104     proc.wait()
105     if proc.returncode != 0:
106         print 'Error in DVI creation for ' + name
107         return
108     # The magnifaction factor is calculated such that we get an image of
109     # height 18 px for most symbols and document font size 11. Then we can
110     # add a small border to get the standard math image height of 20 px.
111     cmd = "dvipng %s.dvi -bg Transparent -D 115 -o %s" % (lyxname, pngname)
112     proc = subprocess.Popen(cmd, shell=True)
113     proc.wait()
114     if proc.returncode != 0:
115         print 'Error in PNG creation for ' + name
116         return
117     image = Image.open(pngname)
118     (width, height) = image.size
119     if width < 20 and height < 20:
120         if width == 19 and height == 19:
121             padded = Image.new('RGBA', (width+1, height+1), (0, 0, 0, 0))
122             padded.paste(image, (0, 0))
123         elif width == 19:
124             padded = Image.new('RGBA', (width+1, height+2), (0, 0, 0, 0))
125             padded.paste(image, (0, 1))
126         elif height == 19:
127             padded = Image.new('RGBA', (width+2, height+1), (0, 0, 0, 0))
128             padded.paste(image, (1, 0))
129         else:
130             padded = Image.new('RGBA', (width+2, height+2), (0, 0, 0, 0))
131             padded.paste(image, (1, 1))
132         padded.convert(image.mode)
133         padded.save(pngname, "PNG")
134
135
136 def main(argv):
137
138     if len(argv) == 3:
139         (base, ext) = os.path.splitext(argv[0])
140         symbols = getlist(argv[1], base)
141         cppfile = os.path.join(os.path.dirname(base), '../../src/frontends/qt4/GuiApplication.cpp')
142         replacements = getreplacements(cppfile)
143         lyxtemplate = base + '.lyx'
144         templatefile = open(base + '.lyx', 'rt')
145         template = templatefile.read()
146         templatefile.close()
147         tempdir = tempfile.mkdtemp()
148         for i in symbols:
149             createimage(i, argv[2], template, argv[1], tempdir, replacements)
150         shutil.rmtree(tempdir)
151     else:
152         error(usage(argv[0]))
153
154     return 0
155
156
157 if __name__ == "__main__":
158     main(sys.argv)