[MERGE] tools.translate: fix extraction of translation terms from mako source files...
[odoo/odoo.git] / openerp / tools / translate.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import codecs
23 import csv
24 import fnmatch
25 import inspect
26 import locale
27 import os
28 import openerp.pooler as pooler
29 import openerp.sql_db as sql_db
30 import re
31 import logging
32 import tarfile
33 import tempfile
34 import threading
35 from babel.messages import extract
36 from os.path import join
37
38 from datetime import datetime
39 from lxml import etree
40
41 import config
42 import misc
43 from misc import UpdateableStr
44 from misc import SKIPPED_ELEMENT_TYPES
45 import osutil
46 from openerp import SUPERUSER_ID
47
48 _logger = logging.getLogger(__name__)
49
50 # used to notify web client that these translations should be loaded in the UI
51 WEB_TRANSLATION_COMMENT = "openerp-web"
52
53 _LOCALE2WIN32 = {
54     'af_ZA': 'Afrikaans_South Africa',
55     'sq_AL': 'Albanian_Albania',
56     'ar_SA': 'Arabic_Saudi Arabia',
57     'eu_ES': 'Basque_Spain',
58     'be_BY': 'Belarusian_Belarus',
59     'bs_BA': 'Serbian (Latin)',
60     'bg_BG': 'Bulgarian_Bulgaria',
61     'ca_ES': 'Catalan_Spain',
62     'hr_HR': 'Croatian_Croatia',
63     'zh_CN': 'Chinese_China',
64     'zh_TW': 'Chinese_Taiwan',
65     'cs_CZ': 'Czech_Czech Republic',
66     'da_DK': 'Danish_Denmark',
67     'nl_NL': 'Dutch_Netherlands',
68     'et_EE': 'Estonian_Estonia',
69     'fa_IR': 'Farsi_Iran',
70     'ph_PH': 'Filipino_Philippines',
71     'fi_FI': 'Finnish_Finland',
72     'fr_FR': 'French_France',
73     'fr_BE': 'French_France',
74     'fr_CH': 'French_France',
75     'fr_CA': 'French_France',
76     'ga': 'Scottish Gaelic',
77     'gl_ES': 'Galician_Spain',
78     'ka_GE': 'Georgian_Georgia',
79     'de_DE': 'German_Germany',
80     'el_GR': 'Greek_Greece',
81     'gu': 'Gujarati_India',
82     'he_IL': 'Hebrew_Israel',
83     'hi_IN': 'Hindi',
84     'hu': 'Hungarian_Hungary',
85     'is_IS': 'Icelandic_Iceland',
86     'id_ID': 'Indonesian_indonesia',
87     'it_IT': 'Italian_Italy',
88     'ja_JP': 'Japanese_Japan',
89     'kn_IN': 'Kannada',
90     'km_KH': 'Khmer',
91     'ko_KR': 'Korean_Korea',
92     'lo_LA': 'Lao_Laos',
93     'lt_LT': 'Lithuanian_Lithuania',
94     'lat': 'Latvian_Latvia',
95     'ml_IN': 'Malayalam_India',
96     'mi_NZ': 'Maori',
97     'mn': 'Cyrillic_Mongolian',
98     'no_NO': 'Norwegian_Norway',
99     'nn_NO': 'Norwegian-Nynorsk_Norway',
100     'pl': 'Polish_Poland',
101     'pt_PT': 'Portuguese_Portugal',
102     'pt_BR': 'Portuguese_Brazil',
103     'ro_RO': 'Romanian_Romania',
104     'ru_RU': 'Russian_Russia',
105     'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro',
106     'sk_SK': 'Slovak_Slovakia',
107     'sl_SI': 'Slovenian_Slovenia',
108     #should find more specific locales for spanish countries,
109     #but better than nothing
110     'es_AR': 'Spanish_Spain',
111     'es_BO': 'Spanish_Spain',
112     'es_CL': 'Spanish_Spain',
113     'es_CO': 'Spanish_Spain',
114     'es_CR': 'Spanish_Spain',
115     'es_DO': 'Spanish_Spain',
116     'es_EC': 'Spanish_Spain',
117     'es_ES': 'Spanish_Spain',
118     'es_GT': 'Spanish_Spain',
119     'es_HN': 'Spanish_Spain',
120     'es_MX': 'Spanish_Spain',
121     'es_NI': 'Spanish_Spain',
122     'es_PA': 'Spanish_Spain',
123     'es_PE': 'Spanish_Spain',
124     'es_PR': 'Spanish_Spain',
125     'es_PY': 'Spanish_Spain',
126     'es_SV': 'Spanish_Spain',
127     'es_UY': 'Spanish_Spain',
128     'es_VE': 'Spanish_Spain',
129     'sv_SE': 'Swedish_Sweden',
130     'ta_IN': 'English_Australia',
131     'th_TH': 'Thai_Thailand',
132     'tr_TR': 'Turkish_Turkey',
133     'uk_UA': 'Ukrainian_Ukraine',
134     'vi_VN': 'Vietnamese_Viet Nam',
135     'tlh_TLH': 'Klingon',
136
137 }
138
139
140 class UNIX_LINE_TERMINATOR(csv.excel):
141     lineterminator = '\n'
142
143 csv.register_dialect("UNIX", UNIX_LINE_TERMINATOR)
144
145 #
146 # Warning: better use self.pool.get('ir.translation')._get_source if you can
147 #
148 def translate(cr, name, source_type, lang, source=None):
149     if source and name:
150         cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s and src=%s', (lang, source_type, str(name), source))
151     elif name:
152         cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s', (lang, source_type, str(name)))
153     elif source:
154         cr.execute('select value from ir_translation where lang=%s and type=%s and src=%s', (lang, source_type, source))
155     res_trans = cr.fetchone()
156     res = res_trans and res_trans[0] or False
157     return res
158
159 class GettextAlias(object):
160
161     def _get_db(self):
162         # find current DB based on thread/worker db name (see netsvc)
163         db_name = getattr(threading.currentThread(), 'dbname', None)
164         if db_name:
165             return sql_db.db_connect(db_name)
166
167     def _get_cr(self, frame, allow_create=True):
168         is_new_cr = False
169         cr = frame.f_locals.get('cr', frame.f_locals.get('cursor'))
170         if not cr:
171             s = frame.f_locals.get('self', {})
172             cr = getattr(s, 'cr', None)
173         if not cr and allow_create:
174             db = self._get_db()
175             if db:
176                 cr = db.cursor()
177                 is_new_cr = True
178         return cr, is_new_cr
179
180     def _get_uid(self, frame):
181         return frame.f_locals.get('uid') or frame.f_locals.get('user')
182
183     def _get_lang(self, frame):
184         lang = None
185         ctx = frame.f_locals.get('context')
186         if not ctx:
187             kwargs = frame.f_locals.get('kwargs')
188             if kwargs is None:
189                 args = frame.f_locals.get('args')
190                 if args and isinstance(args, (list, tuple)) \
191                         and isinstance(args[-1], dict):
192                     ctx = args[-1]
193             elif isinstance(kwargs, dict):
194                 ctx = kwargs.get('context')
195         if ctx:
196             lang = ctx.get('lang')
197         s = frame.f_locals.get('self', {})
198         if not lang:
199             c = getattr(s, 'localcontext', None)
200             if c:
201                 lang = c.get('lang')
202         if not lang:
203             # Last resort: attempt to guess the language of the user
204             # Pitfall: some operations are performed in sudo mode, and we 
205             #          don't know the originial uid, so the language may
206             #          be wrong when the admin language differs.
207             pool = getattr(s, 'pool', None)
208             (cr, dummy) = self._get_cr(frame, allow_create=False)
209             uid = self._get_uid(frame)
210             if pool and cr and uid:
211                 lang = pool.get('res.users').context_get(cr, uid)['lang']
212         return lang
213
214     def __call__(self, source):
215         res = source
216         cr = None
217         is_new_cr = False
218         try:
219             frame = inspect.currentframe()
220             if frame is None:
221                 return source
222             frame = frame.f_back
223             if not frame:
224                 return source
225             lang = self._get_lang(frame)
226             if lang:
227                 cr, is_new_cr = self._get_cr(frame)
228                 if cr:
229                     # Try to use ir.translation to benefit from global cache if possible
230                     pool = pooler.get_pool(cr.dbname)
231                     res = pool.get('ir.translation')._get_source(cr, SUPERUSER_ID, None, ('code','sql_constraint'), lang, source)
232                 else:
233                     _logger.debug('no context cursor detected, skipping translation for "%r"', source)
234             else:
235                 _logger.debug('no translation language detected, skipping translation for "%r" ', source)
236         except Exception:
237             _logger.debug('translation went wrong for "%r", skipped', source)
238                 # if so, double-check the root/base translations filenames
239         finally:
240             if cr and is_new_cr:
241                 cr.close()
242         return res
243
244 _ = GettextAlias()
245
246
247 def quote(s):
248     """Returns quoted PO term string, with special PO characters escaped"""
249     assert r"\n" not in s, "Translation terms may not include escaped newlines ('\\n'), please use only literal newlines! (in '%s')" % s
250     return '"%s"' % s.replace('\\','\\\\') \
251                      .replace('"','\\"') \
252                      .replace('\n', '\\n"\n"')
253
254 re_escaped_char = re.compile(r"(\\.)")
255 re_escaped_replacements = {'n': '\n', }
256
257 def _sub_replacement(match_obj):
258     return re_escaped_replacements.get(match_obj.group(1)[1], match_obj.group(1)[1])
259
260 def unquote(str):
261     """Returns unquoted PO term string, with special PO characters unescaped"""
262     return re_escaped_char.sub(_sub_replacement, str[1:-1])
263
264 # class to handle po files
265 class TinyPoFile(object):
266     def __init__(self, buffer):
267         self.buffer = buffer
268
269     def warn(self, msg, *args):
270         _logger.warning(msg, *args)
271
272     def __iter__(self):
273         self.buffer.seek(0)
274         self.lines = self._get_lines()
275         self.lines_count = len(self.lines)
276
277         self.first = True
278         self.extra_lines= []
279         return self
280
281     def _get_lines(self):
282         lines = self.buffer.readlines()
283         # remove the BOM (Byte Order Mark):
284         if len(lines):
285             lines[0] = unicode(lines[0], 'utf8').lstrip(unicode( codecs.BOM_UTF8, "utf8"))
286
287         lines.append('') # ensure that the file ends with at least an empty line
288         return lines
289
290     def cur_line(self):
291         return self.lines_count - len(self.lines)
292
293     def next(self):
294         trans_type = name = res_id = source = trad = None
295         if self.extra_lines:
296             trans_type, name, res_id, source, trad, comments = self.extra_lines.pop(0)
297             if not res_id:
298                 res_id = '0'
299         else:
300             comments = []
301             targets = []
302             line = None
303             fuzzy = False
304             while not line:
305                 if 0 == len(self.lines):
306                     raise StopIteration()
307                 line = self.lines.pop(0).strip()
308             while line.startswith('#'):
309                 if line.startswith('#~ '):
310                     break
311                 if line.startswith('#.'):
312                     line = line[2:].strip()
313                     if not line.startswith('module:'):
314                         comments.append(line)
315                 elif line.startswith('#:'):
316                     for lpart in line[2:].strip().split(' '):
317                         trans_info = lpart.strip().split(':',2)
318                         if trans_info and len(trans_info) == 2:
319                             # looks like the translation trans_type is missing, which is not
320                             # unexpected because it is not a GetText standard. Default: 'code'
321                             trans_info[:0] = ['code']
322                         if trans_info and len(trans_info) == 3:
323                             # this is a ref line holding the destination info (model, field, record)
324                             targets.append(trans_info)
325                 elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'):
326                     fuzzy = True
327                 line = self.lines.pop(0).strip()
328             while not line:
329                 # allow empty lines between comments and msgid
330                 line = self.lines.pop(0).strip()
331             if line.startswith('#~ '):
332                 while line.startswith('#~ ') or not line.strip():
333                     if 0 == len(self.lines):
334                         raise StopIteration()
335                     line = self.lines.pop(0)
336                 # This has been a deprecated entry, don't return anything
337                 return self.next()
338
339             if not line.startswith('msgid'):
340                 raise Exception("malformed file: bad line: %s" % line)
341             source = unquote(line[6:])
342             line = self.lines.pop(0).strip()
343             if not source and self.first:
344                 # if the source is "" and it's the first msgid, it's the special
345                 # msgstr with the informations about the traduction and the
346                 # traductor; we skip it
347                 self.extra_lines = []
348                 while line:
349                     line = self.lines.pop(0).strip()
350                 return self.next()
351
352             while not line.startswith('msgstr'):
353                 if not line:
354                     raise Exception('malformed file at %d'% self.cur_line())
355                 source += unquote(line)
356                 line = self.lines.pop(0).strip()
357
358             trad = unquote(line[7:])
359             line = self.lines.pop(0).strip()
360             while line:
361                 trad += unquote(line)
362                 line = self.lines.pop(0).strip()
363
364             if targets and not fuzzy:
365                 trans_type, name, res_id = targets.pop(0)
366                 for t, n, r in targets:
367                     if t == trans_type == 'code': continue
368                     self.extra_lines.append((t, n, r, source, trad, comments))
369
370         self.first = False
371
372         if name is None:
373             if not fuzzy:
374                 self.warn('Missing "#:" formated comment at line %d for the following source:\n\t%s',
375                         self.cur_line(), source[:30])
376             return self.next()
377         return trans_type, name, res_id, source, trad, '\n'.join(comments)
378
379     def write_infos(self, modules):
380         import openerp.release as release
381         self.buffer.write("# Translation of %(project)s.\n" \
382                           "# This file contains the translation of the following modules:\n" \
383                           "%(modules)s" \
384                           "#\n" \
385                           "msgid \"\"\n" \
386                           "msgstr \"\"\n" \
387                           '''"Project-Id-Version: %(project)s %(version)s\\n"\n''' \
388                           '''"Report-Msgid-Bugs-To: \\n"\n''' \
389                           '''"POT-Creation-Date: %(now)s\\n"\n'''        \
390                           '''"PO-Revision-Date: %(now)s\\n"\n'''         \
391                           '''"Last-Translator: <>\\n"\n''' \
392                           '''"Language-Team: \\n"\n'''   \
393                           '''"MIME-Version: 1.0\\n"\n''' \
394                           '''"Content-Type: text/plain; charset=UTF-8\\n"\n'''   \
395                           '''"Content-Transfer-Encoding: \\n"\n'''       \
396                           '''"Plural-Forms: \\n"\n'''    \
397                           "\n"
398
399                           % { 'project': release.description,
400                               'version': release.version,
401                               'modules': reduce(lambda s, m: s + "#\t* %s\n" % m, modules, ""),
402                               'now': datetime.utcnow().strftime('%Y-%m-%d %H:%M')+"+0000",
403                             }
404                           )
405
406     def write(self, modules, tnrs, source, trad, comments=None):
407
408         plurial = len(modules) > 1 and 's' or ''
409         self.buffer.write("#. module%s: %s\n" % (plurial, ', '.join(modules)))
410
411         if comments:
412             self.buffer.write(''.join(('#. %s\n' % c for c in comments)))
413
414         code = False
415         for typy, name, res_id in tnrs:
416             self.buffer.write("#: %s:%s:%s\n" % (typy, name, res_id))
417             if typy == 'code':
418                 code = True
419
420         if code:
421             # only strings in python code are python formated
422             self.buffer.write("#, python-format\n")
423
424         if not isinstance(trad, unicode):
425             trad = unicode(trad, 'utf8')
426         if not isinstance(source, unicode):
427             source = unicode(source, 'utf8')
428
429         msg = "msgid %s\n"      \
430               "msgstr %s\n\n"   \
431                   % (quote(source), quote(trad))
432         self.buffer.write(msg.encode('utf8'))
433
434
435 # Methods to export the translation file
436
437 def trans_export(lang, modules, buffer, format, cr):
438
439     def _process(format, modules, rows, buffer, lang):
440         if format == 'csv':
441             writer = csv.writer(buffer, 'UNIX')
442             # write header first
443             writer.writerow(("module","type","name","res_id","src","value"))
444             for module, type, name, res_id, src, trad, comments in rows:
445                 # Comments are ignored by the CSV writer
446                 writer.writerow((module, type, name, res_id, src, trad))
447         elif format == 'po':
448             writer = TinyPoFile(buffer)
449             writer.write_infos(modules)
450
451             # we now group the translations by source. That means one translation per source.
452             grouped_rows = {}
453             for module, type, name, res_id, src, trad, comments in rows:
454                 row = grouped_rows.setdefault(src, {})
455                 row.setdefault('modules', set()).add(module)
456                 if not row.get('translation') and trad != src:
457                     row['translation'] = trad
458                 row.setdefault('tnrs', []).append((type, name, res_id))
459                 row.setdefault('comments', set()).update(comments)
460
461             for src, row in grouped_rows.items():
462                 if not lang:
463                     # translation template, so no translation value
464                     row['translation'] = ''
465                 elif not row.get('translation'):
466                     row['translation'] = src
467                 writer.write(row['modules'], row['tnrs'], src, row['translation'], row['comments'])
468
469         elif format == 'tgz':
470             rows_by_module = {}
471             for row in rows:
472                 module = row[0]
473                 rows_by_module.setdefault(module, []).append(row)
474             tmpdir = tempfile.mkdtemp()
475             for mod, modrows in rows_by_module.items():
476                 tmpmoddir = join(tmpdir, mod, 'i18n')
477                 os.makedirs(tmpmoddir)
478                 pofilename = (lang if lang else mod) + ".po" + ('t' if not lang else '')
479                 buf = file(join(tmpmoddir, pofilename), 'w')
480                 _process('po', [mod], modrows, buf, lang)
481                 buf.close()
482
483             tar = tarfile.open(fileobj=buffer, mode='w|gz')
484             tar.add(tmpdir, '')
485             tar.close()
486
487         else:
488             raise Exception(_('Unrecognized extension: must be one of '
489                 '.csv, .po, or .tgz (received .%s).' % format))
490
491     trans_lang = lang
492     if not trans_lang and format == 'csv':
493         # CSV files are meant for translators and they need a starting point,
494         # so we at least put the original term in the translation column
495         trans_lang = 'en_US'
496     translations = trans_generate(lang, modules, cr)
497     modules = set([t[0] for t in translations[1:]])
498     _process(format, modules, translations, buffer, lang)
499     del translations
500
501 def trans_parse_xsl(de):
502     return list(set(trans_parse_xsl_aux(de, False)))
503
504 def trans_parse_xsl_aux(de, t):
505     res = []
506
507     for n in de:
508         t = t or n.get("t")
509         if t:
510                 if isinstance(n, SKIPPED_ELEMENT_TYPES) or n.tag.startswith('{http://www.w3.org/1999/XSL/Transform}'):
511                     continue
512                 if n.text:
513                     l = n.text.strip().replace('\n',' ')
514                     if len(l):
515                         res.append(l.encode("utf8"))
516                 if n.tail:
517                     l = n.tail.strip().replace('\n',' ')
518                     if len(l):
519                         res.append(l.encode("utf8"))
520         res.extend(trans_parse_xsl_aux(n, t))
521     return res
522
523 def trans_parse_rml(de):
524     res = []
525     for n in de:
526         for m in n:
527             if isinstance(m, SKIPPED_ELEMENT_TYPES) or not m.text:
528                 continue
529             string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.text)]
530             for s in string_list:
531                 if s:
532                     res.append(s.encode("utf8"))
533         res.extend(trans_parse_rml(n))
534     return res
535
536 def trans_parse_view(de):
537     res = []
538     if not isinstance(de, SKIPPED_ELEMENT_TYPES) and de.text and de.text.strip():
539         res.append(de.text.strip().encode("utf8"))
540     if de.tail and de.tail.strip():
541         res.append(de.tail.strip().encode("utf8"))
542     if de.tag == 'attribute' and de.get("name") == 'string':
543         if de.text:
544             res.append(de.text.encode("utf8"))
545     if de.get("string"):
546         res.append(de.get('string').encode("utf8"))
547     if de.get("help"):
548         res.append(de.get('help').encode("utf8"))
549     if de.get("sum"):
550         res.append(de.get('sum').encode("utf8"))
551     if de.get("confirm"):
552         res.append(de.get('confirm').encode("utf8"))
553     for n in de:
554         res.extend(trans_parse_view(n))
555     return res
556
557 # tests whether an object is in a list of modules
558 def in_modules(object_name, modules):
559     if 'all' in modules:
560         return True
561
562     module_dict = {
563         'ir': 'base',
564         'res': 'base',
565         'workflow': 'base',
566     }
567     module = object_name.split('.')[0]
568     module = module_dict.get(module, module)
569     return module in modules
570
571
572 def babel_extract_qweb(fileobj, keywords, comment_tags, options):
573     """Babel message extractor for qweb template files.
574     :param fileobj: the file-like object the messages should be extracted from
575     :param keywords: a list of keywords (i.e. function names) that should
576                      be recognized as translation functions
577     :param comment_tags: a list of translator tags to search for and
578                          include in the results
579     :param options: a dictionary of additional options (optional)
580     :return: an iterator over ``(lineno, funcname, message, comments)``
581              tuples
582     :rtype: ``iterator``
583     """
584     result = []
585     def handle_text(text, lineno):
586         text = (text or "").strip()
587         if len(text) > 1: # Avoid mono-char tokens like ':' ',' etc.
588             result.append((lineno, None, text, []))
589
590     # not using elementTree.iterparse because we need to skip sub-trees in case
591     # the ancestor element had a reason to be skipped
592     def iter_elements(current_element):
593         for el in current_element:
594             if isinstance(el, SKIPPED_ELEMENT_TYPES): continue
595             if "t-js" not in el.attrib and \
596                     not ("t-jquery" in el.attrib and "t-operation" not in el.attrib) and \
597                     not ("t-translation" in el.attrib and el.attrib["t-translation"].strip() == "off"):
598                 handle_text(el.text, el.sourceline)
599                 for att in ('title', 'alt', 'label', 'placeholder'):
600                     if att in el.attrib:
601                         handle_text(el.attrib[att], el.sourceline)
602                 iter_elements(el)
603             handle_text(el.tail, el.sourceline)
604
605     tree = etree.parse(fileobj)
606     iter_elements(tree.getroot())
607
608     return result
609
610
611 def trans_generate(lang, modules, cr):
612     dbname = cr.dbname
613
614     pool = pooler.get_pool(dbname)
615     trans_obj = pool.get('ir.translation')
616     model_data_obj = pool.get('ir.model.data')
617     uid = 1
618     l = pool.models.items()
619     l.sort()
620
621     query = 'SELECT name, model, res_id, module'    \
622             '  FROM ir_model_data'
623
624     query_models = """SELECT m.id, m.model, imd.module
625             FROM ir_model AS m, ir_model_data AS imd
626             WHERE m.id = imd.res_id AND imd.model = 'ir.model' """
627
628     if 'all_installed' in modules:
629         query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') '
630         query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') "
631     query_param = None
632     if 'all' not in modules:
633         query += ' WHERE module IN %s'
634         query_models += ' AND imd.module in %s'
635         query_param = (tuple(modules),)
636     query += ' ORDER BY module, model, name'
637     query_models += ' ORDER BY module, model'
638
639     cr.execute(query, query_param)
640
641     _to_translate = []
642     def push_translation(module, type, name, id, source, comments=None):
643         tuple = (module, source, name, id, type, comments or [])
644         # empty and one-letter terms are ignored, they probably are not meant to be
645         # translated, and would be very hard to translate anyway.
646         if not source or len(source.strip()) <= 1:
647             _logger.debug("Ignoring empty or 1-letter source term: %r", tuple)
648             return
649         if tuple not in _to_translate:
650             _to_translate.append(tuple)
651
652     def encode(s):
653         if isinstance(s, unicode):
654             return s.encode('utf8')
655         return s
656
657     for (xml_name,model,res_id,module) in cr.fetchall():
658         module = encode(module)
659         model = encode(model)
660         xml_name = "%s.%s" % (module, encode(xml_name))
661
662         if not pool.get(model):
663             _logger.error("Unable to find object %r", model)
664             continue
665
666         exists = pool.get(model).exists(cr, uid, res_id)
667         if not exists:
668             _logger.warning("Unable to find object %r with id %d", model, res_id)
669             continue
670         obj = pool.get(model).browse(cr, uid, res_id)
671
672         if model=='ir.ui.view':
673             d = etree.XML(encode(obj.arch))
674             for t in trans_parse_view(d):
675                 push_translation(module, 'view', encode(obj.model), 0, t)
676         elif model=='ir.actions.wizard':
677             service_name = 'wizard.'+encode(obj.wiz_name)
678             import openerp.netsvc as netsvc
679             if netsvc.Service._services.get(service_name):
680                 obj2 = netsvc.Service._services[service_name]
681                 for state_name, state_def in obj2.states.iteritems():
682                     if 'result' in state_def:
683                         result = state_def['result']
684                         if result['type'] != 'form':
685                             continue
686                         name = "%s,%s" % (encode(obj.wiz_name), state_name)
687
688                         def_params = {
689                             'string': ('wizard_field', lambda s: [encode(s)]),
690                             'selection': ('selection', lambda s: [encode(e[1]) for e in ((not callable(s)) and s or [])]),
691                             'help': ('help', lambda s: [encode(s)]),
692                         }
693
694                         # export fields
695                         if not result.has_key('fields'):
696                             _logger.warning("res has no fields: %r", result)
697                             continue
698                         for field_name, field_def in result['fields'].iteritems():
699                             res_name = name + ',' + field_name
700
701                             for fn in def_params:
702                                 if fn in field_def:
703                                     transtype, modifier = def_params[fn]
704                                     for val in modifier(field_def[fn]):
705                                         push_translation(module, transtype, res_name, 0, val)
706
707                         # export arch
708                         arch = result['arch']
709                         if arch and not isinstance(arch, UpdateableStr):
710                             d = etree.XML(arch)
711                             for t in trans_parse_view(d):
712                                 push_translation(module, 'wizard_view', name, 0, t)
713
714                         # export button labels
715                         for but_args in result['state']:
716                             button_name = but_args[0]
717                             button_label = but_args[1]
718                             res_name = name + ',' + button_name
719                             push_translation(module, 'wizard_button', res_name, 0, button_label)
720
721         elif model=='ir.model.fields':
722             try:
723                 field_name = encode(obj.name)
724             except AttributeError, exc:
725                 _logger.error("name error in %s: %s", xml_name, str(exc))
726                 continue
727             objmodel = pool.get(obj.model)
728             if not objmodel or not field_name in objmodel._columns:
729                 continue
730             field_def = objmodel._columns[field_name]
731
732             name = "%s,%s" % (encode(obj.model), field_name)
733             push_translation(module, 'field', name, 0, encode(field_def.string))
734
735             if field_def.help:
736                 push_translation(module, 'help', name, 0, encode(field_def.help))
737
738             if field_def.translate:
739                 ids = objmodel.search(cr, uid, [])
740                 obj_values = objmodel.read(cr, uid, ids, [field_name])
741                 for obj_value in obj_values:
742                     res_id = obj_value['id']
743                     if obj.name in ('ir.model', 'ir.ui.menu'):
744                         res_id = 0
745                     model_data_ids = model_data_obj.search(cr, uid, [
746                         ('model', '=', model),
747                         ('res_id', '=', res_id),
748                         ])
749                     if not model_data_ids:
750                         push_translation(module, 'model', name, 0, encode(obj_value[field_name]))
751
752             if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)):
753                 for dummy, val in field_def.selection:
754                     push_translation(module, 'selection', name, 0, encode(val))
755
756         elif model=='ir.actions.report.xml':
757             name = encode(obj.report_name)
758             fname = ""
759             if obj.report_rml:
760                 fname = obj.report_rml
761                 parse_func = trans_parse_rml
762                 report_type = "report"
763             elif obj.report_xsl:
764                 fname = obj.report_xsl
765                 parse_func = trans_parse_xsl
766                 report_type = "xsl"
767             if fname and obj.report_type in ('pdf', 'xsl'):
768                 try:
769                     report_file = misc.file_open(fname)
770                     try:
771                         d = etree.parse(report_file)
772                         for t in parse_func(d.iter()):
773                             push_translation(module, report_type, name, 0, t)
774                     finally:
775                         report_file.close()
776                 except (IOError, etree.XMLSyntaxError):
777                     _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)
778
779         for field_name,field_def in obj._table._columns.items():
780             if field_def.translate:
781                 name = model + "," + field_name
782                 try:
783                     trad = getattr(obj, field_name) or ''
784                 except:
785                     trad = ''
786                 push_translation(module, 'model', name, xml_name, encode(trad))
787
788         # End of data for ir.model.data query results
789
790     cr.execute(query_models, query_param)
791
792     def push_constraint_msg(module, term_type, model, msg):
793         if not hasattr(msg, '__call__'):
794             push_translation(encode(module), term_type, encode(model), 0, encode(msg))
795
796     def push_local_constraints(module, model, cons_type='sql_constraints'):
797         """Climb up the class hierarchy and ignore inherited constraints
798            from other modules"""
799         term_type = 'sql_constraint' if cons_type == 'sql_constraints' else 'constraint'
800         msg_pos = 2 if cons_type == 'sql_constraints' else 1
801         for cls in model.__class__.__mro__:
802             if getattr(cls, '_module', None) != module:
803                 continue
804             constraints = getattr(cls, '_local_' + cons_type, [])
805             for constraint in constraints:
806                 push_constraint_msg(module, term_type, model._name, constraint[msg_pos])
807             
808     for (_, model, module) in cr.fetchall():
809         model_obj = pool.get(model)
810
811         if not model_obj:
812             _logger.error("Unable to find object %r", model)
813             continue
814
815         if model_obj._constraints:
816             push_local_constraints(module, model_obj, 'constraints')
817
818         if model_obj._sql_constraints:
819             push_local_constraints(module, model_obj, 'sql_constraints')
820
821     def get_module_from_path(path, mod_paths=None):
822         if not mod_paths:
823             # First, construct a list of possible paths
824             def_path = os.path.abspath(os.path.join(config.config['root_path'], 'addons'))     # default addons path (base)
825             ad_paths= map(lambda m: os.path.abspath(m.strip()),config.config['addons_path'].split(','))
826             mod_paths=[def_path]
827             for adp in ad_paths:
828                 mod_paths.append(adp)
829                 if not os.path.isabs(adp):
830                     mod_paths.append(adp)
831                 elif adp.startswith(def_path):
832                     mod_paths.append(adp[len(def_path)+1:])
833         for mp in mod_paths:
834             if path.startswith(mp) and (os.path.dirname(path) != mp):
835                 path = path[len(mp)+1:]
836                 return path.split(os.path.sep)[0]
837         return 'base'   # files that are not in a module are considered as being in 'base' module
838
839     modobj = pool.get('ir.module.module')
840     installed_modids = modobj.search(cr, uid, [('state', '=', 'installed')])
841     installed_modules = map(lambda m: m['name'], modobj.read(cr, uid, installed_modids, ['name']))
842
843     root_path = os.path.join(config.config['root_path'], 'addons')
844
845     apaths = map(os.path.abspath, map(str.strip, config.config['addons_path'].split(',')))
846     if root_path in apaths:
847         path_list = apaths
848     else :
849         path_list = [root_path,] + apaths
850
851     # Also scan these non-addon paths
852     for bin_path in ['osv', 'report' ]:
853         path_list.append(os.path.join(config.config['root_path'], bin_path))
854
855     _logger.debug("Scanning modules at paths: ", path_list)
856
857     mod_paths = []
858
859     def verified_module_filepaths(fname, path, root):
860         fabsolutepath = join(root, fname)
861         frelativepath = fabsolutepath[len(path):]
862         display_path = "addons%s" % frelativepath
863         module = get_module_from_path(fabsolutepath, mod_paths=mod_paths)
864         if ('all' in modules or module in modules) and module in installed_modules:
865             return module, fabsolutepath, frelativepath, display_path
866         return None, None, None, None
867
868     def babel_extract_terms(fname, path, root, extract_method="python", trans_type='code',
869                                extra_comments=None, extract_keywords={'_': None}):
870         module, fabsolutepath, _, display_path = verified_module_filepaths(fname, path, root)
871         extra_comments = extra_comments or []
872         if module:
873             src_file = open(fabsolutepath, 'r')
874             try:
875                 for lineno, message, comments in extract.extract(extract_method, src_file,
876                                                                  keywords=extract_keywords):
877                     push_translation(module, trans_type, display_path, lineno,
878                                      encode(message), comments + extra_comments)
879             except Exception:
880                 _logger.exception("Failed to extract terms from %s", fabsolutepath)
881             finally:
882                 src_file.close()
883
884     for path in path_list:
885         _logger.debug("Scanning files of modules at %s", path)
886         for root, dummy, files in osutil.walksymlinks(path):
887             for fname in fnmatch.filter(files, '*.py'):
888                 babel_extract_terms(fname, path, root)
889             # mako provides a babel extractor: http://docs.makotemplates.org/en/latest/usage.html#babel
890             for fname in fnmatch.filter(files, '*.mako'):
891                 babel_extract_terms(fname, path, root, 'mako', trans_type='report')
892             # Javascript source files in the static/src/js directory, rest is ignored (libs)
893             if fnmatch.fnmatch(root, '*/static/src/js*'):
894                 for fname in fnmatch.filter(files, '*.js'):
895                     babel_extract_terms(fname, path, root, 'javascript',
896                                         extra_comments=[WEB_TRANSLATION_COMMENT],
897                                         extract_keywords={'_t': None, '_lt': None})
898             # QWeb template files
899             if fnmatch.fnmatch(root, '*/static/src/xml*'):
900                 for fname in fnmatch.filter(files, '*.xml'):
901                     babel_extract_terms(fname, path, root, 'openerp.tools.translate:babel_extract_qweb',
902                                         extra_comments=[WEB_TRANSLATION_COMMENT])
903
904     out = []
905     _to_translate.sort()
906     # translate strings marked as to be translated
907     for module, source, name, id, type, comments in _to_translate:
908         trans = '' if not lang else trans_obj._get_source(cr, uid, name, type, lang, source)
909         out.append([module, type, name, id, source, encode(trans) or '', comments])
910     return out
911
912 def trans_load(cr, filename, lang, verbose=True, module_name=None, context=None):
913     try:
914         fileobj = misc.file_open(filename)
915         _logger.info("loading %s", filename)
916         fileformat = os.path.splitext(filename)[-1][1:].lower()
917         result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context)
918         fileobj.close()
919         return result
920     except IOError:
921         if verbose:
922             _logger.error("couldn't read translation file %s", filename)
923         return None
924
925 def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None):
926     """Populates the ir_translation table."""
927     if verbose:
928         _logger.info('loading translation file for language %s', lang)
929     if context is None:
930         context = {}
931     db_name = cr.dbname
932     pool = pooler.get_pool(db_name)
933     lang_obj = pool.get('res.lang')
934     trans_obj = pool.get('ir.translation')
935     iso_lang = misc.get_iso_codes(lang)
936     try:
937         ids = lang_obj.search(cr, SUPERUSER_ID, [('code','=', lang)])
938
939         if not ids:
940             # lets create the language with locale information
941             lang_obj.load_lang(cr, SUPERUSER_ID, lang=lang, lang_name=lang_name)
942
943
944         # now, the serious things: we read the language file
945         fileobj.seek(0)
946         if fileformat == 'csv':
947             reader = csv.reader(fileobj, quotechar='"', delimiter=',')
948             # read the first line of the file (it contains columns titles)
949             for row in reader:
950                 f = row
951                 break
952         elif fileformat == 'po':
953             reader = TinyPoFile(fileobj)
954             f = ['type', 'name', 'res_id', 'src', 'value', 'comments']
955         else:
956             _logger.error('Bad file format: %s', fileformat)
957             raise Exception(_('Bad file format'))
958
959         # read the rest of the file
960         line = 1
961         irt_cursor = trans_obj._get_import_cursor(cr, SUPERUSER_ID, context=context)
962
963         for row in reader:
964             line += 1
965             # skip empty rows and rows where the translation field (=last fiefd) is empty
966             #if (not row) or (not row[-1]):
967             #    continue
968
969             # dictionary which holds values for this line of the csv file
970             # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
971             #  'src': ..., 'value': ..., 'module':...}
972             dic = dict.fromkeys(('name', 'res_id', 'src', 'type', 'imd_model', 'imd_name', 'module', 'value', 'comments'))
973             dic['lang'] = lang
974             for i, field in enumerate(f):
975                 dic[field] = row[i]
976
977             # This would skip terms that fail to specify a res_id
978             if not dic.get('res_id'):
979                 continue
980
981             res_id = dic.pop('res_id')
982             if res_id and isinstance(res_id, (int, long)) \
983                 or (isinstance(res_id, basestring) and res_id.isdigit()):
984                     dic['res_id'] = int(res_id)
985                     dic['module'] = module_name
986             else:
987                 tmodel = dic['name'].split(',')[0]
988                 if '.' in res_id:
989                     tmodule, tname = res_id.split('.', 1)
990                 else:
991                     tmodule = False
992                     tname = res_id
993                 dic['imd_model'] = tmodel
994                 dic['imd_name'] =  tname
995                 dic['module'] = tmodule
996                 dic['res_id'] = None
997
998             irt_cursor.push(dic)
999
1000         irt_cursor.finish()
1001         if verbose:
1002             _logger.info("translation file loaded succesfully")
1003     except IOError:
1004         filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
1005         _logger.exception("couldn't read translation file %s", filename)
1006
1007 def get_locales(lang=None):
1008     if lang is None:
1009         lang = locale.getdefaultlocale()[0]
1010
1011     if os.name == 'nt':
1012         lang = _LOCALE2WIN32.get(lang, lang)
1013
1014     def process(enc):
1015         ln = locale._build_localename((lang, enc))
1016         yield ln
1017         nln = locale.normalize(ln)
1018         if nln != ln:
1019             yield nln
1020
1021     for x in process('utf8'): yield x
1022
1023     prefenc = locale.getpreferredencoding()
1024     if prefenc:
1025         for x in process(prefenc): yield x
1026
1027         prefenc = {
1028             'latin1': 'latin9',
1029             'iso-8859-1': 'iso8859-15',
1030             'cp1252': '1252',
1031         }.get(prefenc.lower())
1032         if prefenc:
1033             for x in process(prefenc): yield x
1034
1035     yield lang
1036
1037
1038
1039 def resetlocale():
1040     # locale.resetlocale is bugged with some locales.
1041     for ln in get_locales():
1042         try:
1043             return locale.setlocale(locale.LC_ALL, ln)
1044         except locale.Error:
1045             continue
1046
1047 def load_language(cr, lang):
1048     """Loads a translation terms for a language.
1049     Used mainly to automate language loading at db initialization.
1050
1051     :param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE')
1052     :type lang: str
1053     """
1054     pool = pooler.get_pool(cr.dbname)
1055     language_installer = pool.get('base.language.install')
1056     uid = 1
1057     oid = language_installer.create(cr, uid, {'lang': lang})
1058     language_installer.lang_install(cr, uid, [oid], context=None)
1059
1060 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
1061