3 # Part of Objavi2, which turns html manuals into books.
4 # This python script generates lists of fonts in pdf and html form.
6 # Copyright (C) 2009 Douglas Bagnall
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with this program; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 from objavi import config
23 import tempfile, os, re, sys
26 from subprocess import Popen, check_call, PIPE
29 p = Popen(['fc-list'], stdout=PIPE, stderr=PIPE)
30 out, err = p.communicate()
31 fonts = set(re.findall(r"^([^:,]+)", out.strip().replace('\-', '-'), re.M))
32 return sorted(fonts, key=str.lower)
35 def font_html(fonts, example_template, dir="LTR"):
36 html = ['<html dir="%s"><meta http-equiv="content-type" content="text/html; charset=utf-8"> <style>'
37 '.font-name {background: #ffc; padding: 0.25em; font-family: "Dejavu Sans", sans-serif}'
38 ' div{padding:0.9em 0}'
39 '</style><body>' % dir]
41 html.append(example_template % {'font':f})
42 html.append('</body></html>')
43 return '\n'.join(html)
45 def font_pdf(html, pdfname):
46 fh, htmlname = tempfile.mkstemp(suffix='.html', dir=config.TMPDIR)
49 cmd = ['xvfb-run', config.WKHTMLTOPDF, '-q', '-s', 'A4',
52 p = Popen(cmd, stdout=PIPE, stderr=PIPE)
53 print >>sys.stderr, p.communicate()
55 def html_font_list(fonts, name):
61 #Instead of regenerating the pdf every time, which is expensive, keep
62 #a cached version indexed by the font list and script version
63 fonts = get_font_list()
64 h = hashlib.sha1(str(fonts))
66 #Any change to this file will effectively clear the cache.
71 #XXX should also include the script example include in the hash
73 form = cgi.FieldStorage()
74 script = form.getfirst('script')
75 if script not in (x for x in os.listdir(config.FONT_EXAMPLE_SCRIPT_DIR) if x.isalnum()):
78 pdfname = os.path.join(config.BOOK_LIST_CACHE_DIR, 'font-list-%s-%s.pdf' %(script, h.hexdigest()))
80 if not os.path.exists(pdfname):
81 #So this particular font list has not been made before
82 f = open(os.path.join(config.FONT_EXAMPLE_SCRIPT_DIR, script))
83 example_template = f.read()
86 if script in config.RTL_SCRIPTS:
88 html = font_html(fonts, example_template, dir)
89 font_pdf(html, pdfname)
91 include_name = os.path.join(config.BOOK_LIST_CACHE_DIR, 'font-list.inc')
92 html_font_list(fonts, include_name)
96 print "Content-type: application/pdf\n"