forked from gcompris/GCompris-site
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcompris.py
executable file
·338 lines (281 loc) · 9.82 KB
/
gcompris.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/python
# -*- coding: utf-8 -*-
import codecs
import os
import sys
import jinja2
from datetime import date
import sqlite3
import re
from collections import OrderedDict
import gettext
today = date.today()
try:
version = sys.argv[1]
except:
print "Missing GCompris version"
sys.exit(1)
try:
locale = sys.argv[2]
except:
print "Missing GCompris locale"
sys.exit(1)
try:
localelist = sys.argv[3]
except:
print "Missing GCompris list of locales"
sys.exit(1)
# Load the proper locale catalog
_ = None
t = None
def setLocale(locale):
global _
global t
try:
t = gettext.translation('gcompris', 'locale', languages=[locale])
except:
t = gettext.NullTranslations()
_ = t.ugettext
def formatDate(date):
return date[0:4] + '-' + date[4:6] + '-' + date[6:8]
#
# Parse the config.c file in GCompris source code to get
# the name of the given locale.
#
def getLocaleName(locale):
result = locale
with open("/home/bcoudoin/Projets/gcompris/src/gcompris/config.c", 'r') as f:
inlist = False
for line in f:
line = line.rstrip()
if line.startswith("static gchar *linguas[]"):
inlist = True
continue
if line == "};":
break
if not inlist:
continue
sline = line.split(',')
if sline[0].strip(' "').startswith(locale):
result = sline[1].strip().replace('N_("', '').replace('")', '')
break
return result
# Set the default locale
setLocale(locale)
#
# Create locales [ [ locale, language ], ...]
#
locales = []
language = ""
for loca in localelist.split():
# We want each country in its own language
setLocale(loca)
lang = _(getLocaleName( loca ))
locales.append( ['-' + loca, lang] )
if locale == loca:
language = lang
# Add en_US manually
setLocale("en")
locales.append( ['-en', _(getLocaleName( 'en_US'))] )
if language == '':
language = 'English'
# Back to the default locale
setLocale(locale)
locales = sorted(locales, key=lambda t: t[1])
suffix = '-' + locale
#
# We don't have a translation of each manual. If we have it
# we return it else we return the english one
def getManual():
manuals = {
'en': 'wiki/Manual',
'fr': 'wiki/Manuel',
'de': 'wiki/Benutzerhandbuch',
'es': 'wiki/Manual_es',
'pt_BR': 'wiki/Manual_pt-BR',
'he': u'wiki/מדריך_למשתמש',
'ru': u'wiki/Руководство'
}
if locale in manuals:
return manuals[locale]
return manuals['en']
def getBoards():
con = sqlite3.connect("/home/bcoudoin/.config/gcompris/gcompris_sqlite.db")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute('select name, section, author, difficulty, icon, title, description, prerequisite, goal, manual, credit, demo, type from boards order by section||\'/\'||name, difficulty')
# Make a dict rw of the result
return [dict(row) for row in cur]
# /a/b /a => 1 0
# /a/b /c => 2 1
# /a/b /a/b => 0 0
# /a '' => 1 0
# /a/b/c/d /a/b/e/f => 2 2
# /a /a/b/c => 0 2
#
# Return (open, close)
#
def sectionDiff(old, new):
if old == new:
return (0, 0)
olds = old.split("/")
news = new.split("/")
closes = 0
opens = 0
for i in range(0, max(len(olds), len(news)) ):
try:
if olds[i] == news[i]:
continue
else:
closes += 1
opens += 1
except:
if len(olds) > i:
closes += 1
else:
opens += 1
return (opens, closes)
templateLoader = jinja2.FileSystemLoader( searchpath="." )
templateEnv = jinja2.Environment( loader=templateLoader,
extensions=['jinja2.ext.i18n'] )
templateEnv.install_gettext_callables(t.ugettext, t.ungettext, newstyle=True)
# Specify any input variables to the template as a dictionary.
templateVars = {
"locale" : locale,
"suffix" : suffix,
"language" : language,
"title" : "GCompris Free Educational Software",
"revision_date" : today.strftime("%Y-%m-%d"),
"current_year": today.strftime("%Y"),
"version": version,
"news": [],
"screenshots": [],
"screenshotsmenu": [],
"locales": locales,
"manual": getManual(),
"manualTranslation": _("Manual"),
"license_info": _("This software is a GNU Package and is released under the GNU General Public License")
}
# Use this filter in template when you know the text comes from the
# software part and should not be added to the web site po file.
def trans(text):
return _(text)
templateEnv.filters['trans'] = trans
#
# Build a map of all news file to proceed for our locale
#
filenames = {}
for filename in os.listdir("news"):
if not filename.endswith(".html"):
continue
# If a news is found with a -<LOCALE> suffix before .html
# It supercede a news without a such suffix (english one).
filename_noext = filename.split('.')[0]
try:
(dat, loc) = filename_noext.split('-')
if locale == loc:
filenames[dat] = filename
except:
if not filename_noext in filenames:
filenames[filename_noext] = filename
for filename in sorted(filenames, reverse=True):
filename = filenames[filename]
templateOneNews = templateEnv.get_template( "news/" + filename )
templateVars['newsDate'] = formatDate(filename)
templateVars['fileName'] = filename
templateVars["news"].append(templateOneNews.render( templateVars ))
templateNews = templateEnv.get_template( "template/news.html" )
outputNewsText = templateNews.render( templateVars )
templateNewsAll = templateEnv.get_template( "template/newsall.html" )
outputNewsAllText = templateNewsAll.render( templateVars )
#
# Get the board list and make some adaptations
#
boards = getBoards()
for screenshot in boards:
if screenshot['name'] == "":
screenshot['name'] = 'root'
screenshot['section'] = '/administration'
screenshot['type'] = 'root menu'
if screenshot['name'] == "login":
screenshot['section'] = '/administration'
boards = sorted(boards, key=lambda t: t['section']+'/'+t['name'])
# Reorder root, administration and login boards
boards[0], boards[1], boards[2] = boards[2], boards[0], boards[1]
#
# Now process the board list
#
templateScreenshot = templateEnv.get_template( "template/screenshot.html" )
previousSection = ''
depth = 0
for screenshot in boards:
if screenshot['section'] == '/experimental' or screenshot['name'] == 'experimental':
continue
section = screenshot['section']
if screenshot['type'] == 'menu':
section += "/" + screenshot['name']
(opens, closes) = sectionDiff(previousSection, section)
depth += opens - closes
if closes:
templateVars["screenshots"].append("</div>" * closes)
if opens:
templateVars["screenshots"].append("<div class='row screenshot" + str(depth) + "'>" * opens)
previousSection = section
screenshot['icon'] = screenshot['icon'].replace(".svg", "")
screenshot['icon'] = screenshot['icon'].replace(".png", "")
screenshot['author'] = re.sub(r" \(.*\)", "", screenshot['author'])
if screenshot['goal']:
screenshot['goal'] = _(screenshot['goal']).replace('\n', '<br/>')
if screenshot['prerequisite']:
screenshot['prerequisite'] = _(screenshot['prerequisite']).replace('\n', '<br/>')
if screenshot['manual']:
screenshot['manual'] = _(screenshot['manual']).replace('\n', '<br/>')
if screenshot['credit']:
screenshot['credit'] = _(screenshot['credit']).replace('\n', '<br/>')
if screenshot['title']:
screenshot['title'] = _(screenshot['title'])
if screenshot['description']:
screenshot['description'] = _(screenshot['description'])
templateVars["screenshot"] = screenshot
screenshot["depth"] = depth
templateVars["depth"] = depth
templateVars["screenshots"].append(templateScreenshot.render( templateVars ))
# Create the screenshot menu
templateVars["screenshotsmenu"].append(screenshot)
(opens, closes) = sectionDiff(previousSection, '')
templateVars["screenshots"].append("</div>" * closes)
templateScreenshots = templateEnv.get_template( "template/screenshots.html" )
outputScreenshotsText = templateScreenshots.render( templateVars )
# Count the number of activities
demo_activities = 0
total_activities = 0
for screenshot in boards:
if screenshot['type'] != 'menu':
total_activities += 1
if screenshot['demo'] == 1:
demo_activities += 1
templateVars['total_activities'] = total_activities
templateVars['demo_activities'] = demo_activities
templateBuy = templateEnv.get_template( "template/buy.html" )
outputBuyText = templateBuy.render( templateVars )
templateIndex = templateEnv.get_template( "template/index.html" )
outputIndexText = templateIndex.render( templateVars )
with codecs.open('index' + suffix + '.html', 'w', encoding='utf8') as f:
f.write( outputIndexText )
with codecs.open('news' + suffix + '.html', 'w', encoding='utf8') as f:
f.write( outputNewsText )
with codecs.open('newsall' + suffix + '.html', 'w', encoding='utf8') as f:
f.write( outputNewsAllText )
with codecs.open('screenshots' + suffix + '.html', 'w', encoding='utf8') as f:
f.write( outputScreenshotsText )
with codecs.open('buy' + suffix + '.html', 'w', encoding='utf8') as f:
f.write( outputBuyText )
template = templateEnv.get_template( "template/download_macosx.html" )
outputText = template.render( templateVars )
with codecs.open('download_macosx' + suffix + '.html', 'w', encoding='utf8') as f:
f.write( outputText )
if suffix == '-en':
template = templateEnv.get_template( "template/404.html" )
outputText = template.render( templateVars )
with codecs.open('404.html', 'w', encoding='utf8') as f:
f.write( outputText )