]> git.donarmstrong.com Git - lilypond.git/blob - buildscripts/add_html_footer.py
Merge branch 'Rmaster' into topic/master-translation
[lilypond.git] / buildscripts / add_html_footer.py
1 #!@PYTHON@
2
3 """
4 Print a nice footer.
5 """
6 import re
7 import os
8 import time
9
10 import langdefs
11
12 # This is to try to make the docball not too big with almost duplicate files
13 # see process_links()
14 non_copied_pages = ['Documentation/user/out-www/lilypond-big-page',
15                     'Documentation/user/out-www/lilypond-internals-big-page',
16                     'Documentation/user/out-www/music-glossary-big-page',
17                     'out-www/examples',
18                     'Documentation/topdocs',
19                     'Documentation/bibliography',
20                     'Documentation/out-www/THANKS',
21                     'Documentation/out-www/DEDICATION',
22                     'input/']
23
24 def _doc (s):
25     return s
26
27 header = r"""
28 """
29
30 footer = '''
31 <div style="background-color: #e8ffe8; padding: 2; border: #c0ffc0 1px solid;">
32 <p>
33 <font size="-1">
34 %(footer_name_version)s
35 <br>
36 </font>
37 <address><font size="-1">
38 %(footer_report_errors)s </font></address>
39 </p>
40 </div>
41 '''
42 footer_name_version = _doc ('This page is for %(package_name)s-%(package_version)s (%(branch_str)s).')
43 footer_report_errors = _doc ('Report errors to <a href="%(mail_address_url)s">%(mail_address)s</a>.')
44
45 mail_address = 'http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs'
46
47 header_tag = '<!-- header_tag -->'
48 footer_tag = '<!-- footer_tag -->'
49
50 lang_available = _doc ("Other languages: %s.")
51 browser_lang = _doc ('About <A HREF="%s">automatic language selection</A>.')
52 browser_language_url = "/web/about/browser-language"
53
54 LANGUAGES_TEMPLATE = '''
55 <P>
56  %(language_available)s
57  <BR>
58  %(browser_language)s
59 </P>
60 '''
61
62
63 html_re = re.compile ('(.*?)(?:[.]([^/.]*))?[.]html$')
64 pages_dict = {}
65
66 def build_pages_dict (filelist):
67     """Build dictionnary of available translations of each page"""
68     global pages_dict
69     for f in filelist:
70         m = html_re.match (f)
71         if m:
72             g = m.groups()
73             if len (g) <= 1 or g[1] == None:
74                 e = ''
75             else:
76                 e = g[1]
77             if not g[0] in pages_dict.keys():
78                 pages_dict[g[0]] = [e]
79             else:
80                 pages_dict[g[0]].append (e)
81
82 def source_links_replace (m, source_val):
83     return 'href="' + os.path.join (source_val, m.group (1)) + '"'
84
85 splitted_docs_re = re.compile ('Documentation/user/out-www/(lilypond|music-glossary)/')
86
87 # On systems without symlinks (e.g. Windows), docs are not very usable
88 # Get rid of symlinks references here
89 # Get rid of symlinks in GNUmakefile.in (local-WWW-post)
90 def replace_symlinks_urls (s, prefix):
91     if splitted_docs_re.match (prefix):
92         s = re.sub ('(href|src)="(lily-.*?|.*?-flat-.*?)"', '\\1="../\\2"', s)
93     source_path = os.path.join (os.path.dirname (prefix), 'source')
94     if not os.path.islink (source_path):
95         return s
96     source_val = os.readlink (source_path)
97     return re.sub ('href="source/(.*?)"', lambda m: source_links_replace (m, source_val), s)
98
99 def add_header (s):
100     """Add header (<BODY> and doctype)"""
101     if re.search (header_tag, s) == None:
102         body = '<BODY BGCOLOR=WHITE TEXT=BLACK>'
103         s = re.sub ('(?i)<body>', body, s)
104         if re.search ('(?i)<BODY', s):
105             s = re.sub ('(?i)<body[^>]*>', body + header, s, 1)
106         elif re.search ('(?i)<html', s):
107             s = re.sub ('(?i)<html>', '<HTML>' + header, s, 1)
108         else:
109             s = header + s
110
111         s = header_tag + '\n' + s
112
113         if re.search ('(?i)<!DOCTYPE', s) == None:
114             doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n'
115             s = doctype + s
116         return s
117
118 def add_title (s):
119     # urg
120     # maybe find first node?
121     fallback_web_title = '-- --'
122     m = re.match ('.*?<title>(.*?)</title>', s, re.DOTALL)
123     if m:
124         fallback_web_title = m.group (1)
125     s = re.sub ('@WEB-TITLE@', fallback_web_title, s)
126     return s
127
128 info_nav_bar = re.compile (r'<div class="node">\s*<p>\s*<a name=".+?"></a>(.+?)<hr>\s*</div>', re.M | re.S)
129 info_footnote_hr = re.compile (r'<hr>\s*(</div>)?\s*</body>', re.M | re.I)
130
131 def add_footer (s):
132     """add footer
133
134 also add navigation bar to bottom of Info HTML pages"""
135     m = info_nav_bar.search (s)
136     if m:
137         # avoid duplicate <hr> in case there are footnotes at the end of the Info HTML page
138         if info_footnote_hr.search (s):
139             custom_footer = '<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
140         else:
141             custom_footer = '<br><hr>\n<div class="node">\n<p>' + m.group (1) + '</div>\n' + footer
142     else:
143         custom_footer = footer
144     if re.search ('(?i)</body', s):
145         s = re.sub ('(?i)</body>', footer_tag + custom_footer + '\n' + '</BODY>', s, 1)
146     elif re.search ('(?i)</html', s):                
147         s = re.sub ('(?i)</html>', footer_tag + custom_footer + '\n' + '</HTML>', s, 1)
148     else:
149         s += footer_tag + custom_footer + '\n'
150     return s
151
152 def find_translations (prefix, lang_ext):
153     """find available translations of a page"""
154     available = []
155     missing = []
156     for l in langdefs.LANGUAGES:
157         e = l.webext
158         if lang_ext != e:
159             if e in pages_dict[prefix]:
160                 available.append (l)
161             elif lang_ext == '' and l.enabled and reduce (lambda x, y: x and y, [not prefix.startswith (s) for s in non_copied_pages]):
162                 # English version of missing translated pages will be written
163                 missing.append (e)
164     return available, missing
165
166 def process_links (s, prefix, lang_ext, file_name, missing, target):
167     page_flavors = {}
168     if target == 'online':
169         # Strip .html, .png suffix for auto language selection (content
170         # negotiation).  The menu must keep the full extension, so do
171         # this before adding the menu.
172         page_flavors[file_name] = [lang_ext, re.sub (
173             '''(href|src)=[\'"]([^/][.]*[^.:\'"]*)(.html|.png)(#[^"\']*|)[\'"]''',
174             '\\1="\\2\\4"', s)]
175     elif target == 'offline':
176         # in LANG doc index: don't rewrite .html suffixes as not all .LANG.html pages exist
177         # the doc index should be translated and contain the right links
178         if prefix == 'Documentation/out-www/index':
179             page_flavors[file_name] = [lang_ext, s]
180         elif lang_ext == '':
181             page_flavors[file_name] = [lang_ext, s]
182             for e in missing:
183                 page_flavors[langdefs.lang_file_name (prefix, e, '.html')] = [e, re.sub (
184                     '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
185                     'href="\\1.' + e + '\\2\\3"', s)]
186         else:
187             page_flavors[file_name] = [lang_ext, re.sub (
188                 '''href=[\'"]([^/][.]*[^.:\'"]*)(.html)(#[^"\']*|)[\'"]''',
189                 'href="\\1.' + lang_ext + '\\2\\3"', s)]
190     return page_flavors
191
192 def add_menu (page_flavors, prefix, available, target, translation):
193     for k in page_flavors.keys():
194         language_menu = ''
195         languages = ''
196         if page_flavors[k][0] != '':
197             t = translation[page_flavors[k][0]]
198         else:
199             t = _doc
200         for lang in available:
201             lang_file = lang.file_name (os.path.basename (prefix), '.html')
202             if language_menu != '':
203                 language_menu += ', '
204             language_menu += '<a href="%s">%s</a>' % (lang_file, t (lang.name))
205         if target == 'offline':
206             browser_language = ''
207         elif target == 'online':
208             browser_language = t (browser_lang) % browser_language_url
209         if language_menu:
210             language_available = t (lang_available) % language_menu
211             languages = LANGUAGES_TEMPLATE % vars ()
212         # put language menu before '</body>' and '</html>' tags
213         if re.search ('(?i)</body', page_flavors[k][1]):
214             page_flavors[k][1] = re.sub ('(?i)</body>', languages + '</BODY>', page_flavors[k][1], 1)
215         elif re.search ('(?i)</html', page_flavors[k][1]):
216             page_flavors[k][1] = re.sub ('(?i)</html>', languages + '</HTML>', page_flavors[k][1], 1)
217         else:
218             page_flavors[k][1] += languages
219     return page_flavors
220
221
222 def add_html_footer (translation,
223                      package_name = '',
224                      package_version = '',
225                      target = 'offline',
226                      name_filter = lambda s: s):
227     """Add header, footer to a number of HTML files
228
229     Arguments:
230      translation               gettext translations dictionary, with language codes as keys
231      package_name=NAME         set package_name to NAME
232      package_version=VERSION   set package version to VERSION
233      targets=offline|online    set page processing depending on the target
234           offline is for reading HTML pages locally
235           online is for hosting the HTML pages on a website with content
236             negotiation
237      name_filter               a HTML file name filter
238     """
239     localtime = time.strftime ('%c %Z', time.localtime (time.time ()))
240
241     if re.search ("http://", mail_address):
242         mail_address_url = mail_address
243     else:
244         mail_address_url= 'mailto:' + mail_address
245
246     versiontup = package_version.split ('.')
247     branch_str = _doc ('stable-branch')
248     if int (versiontup[1]) %  2:
249         branch_str = _doc ('development-branch')
250
251     for prefix, ext_list in pages_dict.items ():
252         for lang_ext in ext_list:
253             file_name = langdefs.lang_file_name (prefix, lang_ext, '.html')
254             in_f = open (file_name)
255             s = in_f.read()
256             in_f.close()
257
258             s = re.sub ('%', '%%', s)
259             if target == 'offline':
260                 s = replace_symlinks_urls (s, prefix)
261             s = add_header (s)
262
263             ### add footer
264             if re.search (footer_tag, s) == None:
265                 s = add_footer (s)
266                 
267                 available, missing = find_translations (prefix, lang_ext)
268                 page_flavors = process_links (s, prefix, lang_ext, file_name, missing, target)
269                 # Add menu after stripping: must not have autoselection for language menu.
270                 page_flavors = add_menu (page_flavors, prefix, available, target, translation)
271             subst = dict ([i for i in globals().items() if type (i[1]) is str])
272             subst.update (dict ([i for i in locals().items() if type (i[1]) is str]))
273             for k in page_flavors.keys():
274                 if page_flavors[k][0] in translation.keys():
275                     for name in subst.keys():
276                         subst[name] = translation[page_flavors[k][0]] (subst[name])
277                 subst['footer_name_version'] = subst['footer_name_version'] % subst
278                 subst['footer_report_errors'] = subst['footer_report_errors'] % subst
279                 page_flavors[k][1] = page_flavors[k][1] % subst
280                 out_f = open (name_filter (k), 'w')
281                 out_f.write (page_flavors[k][1])
282                 out_f.close()
283         # if the page is translated, a .en.html symlink is necessary for content negotiation
284         if target == 'online' and ext_list != ['']:
285             os.symlink (os.path.basename (prefix) + '.html', name_filter (prefix + '.en.html'))