Package Camelot :: Package camelot :: Package model :: Module i18n |
[frames] | no frames]

# Source Code for Module Camelot.camelot.model.i18n

      1  #  =============================================================================

      2  #

      3  #  Copyright (C) 2007-2008 Conceptive Engineering bvba. All rights reserved.

      4  #  www.conceptive.be / project-camelot@conceptive.be

      5  #

      6  #  This file is part of the Camelot Library.

      7  #

      8  #  This file may be used under the terms of the GNU General Public

      9  #  License version 2.0 as published by the Free Software Foundation

     10  #  and appearing in the file LICENSE.GPL included in the packaging of

     11  #  this file.  Please review the following information to ensure GNU

     12  #  General Public Licensing requirements will be met:

     13  #  http://www.trolltech.com/products/qt/opensource.html

     14  #

     15  #  If you are unsure which license is appropriate for your use, please

     16  #  review the following information:

     17  #  http://www.trolltech.com/products/qt/licensing.html or contact

     18  #  project-camelot@conceptive.be.

     19  #

     20  #  This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE

     21  #  WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

     22  #

     23  #  For use of this library in commercial applications, please contact

     24  #  project-camelot@conceptive.be

     25  #

     26  #  =============================================================================

     27  from camelot.model import metadata
     28  from camelot.admin.list_action import ListAction
     29  import camelot.types
     30  from elixir.entity import Entity
     31  from elixir.options import using_options
     32  from elixir.fields import Field
     33  from sqlalchemy.types import Unicode, INT
     34  """Set of classes to enable internationalization of the user interface"""
     35

     36

     37  __metadata__ = metadata
     38

     39  from camelot.view.elixir_admin import EntityAdmin
     40  from camelot.view.art import Icon
     41  from camelot.core.utils import ugettext_lazy as _
     42

     43  import logging
     44  logger = logging.getLogger( 'camelot.model.i18n' )
     45

     46 -def tr( source ):
     47      from PyQt4 import QtCore
     48      language = unicode( QtCore.QLocale().name() )
     49      return Translation.translate_or_register( source, language )
     50

     51 -class ExportAsPO(ListAction):
     52

     53 -    def __init__(self):
     54          super(ExportAsPO, self).__init__(name=_('po export'),

     55                                           icon=Icon('tango/16x16/actions/document-save.png'))
     56

     57 -    def run( self, collection_getter, selection_getter ):
     58          from PyQt4 import QtGui
     59          from camelot.view.model_thread import post
     60          from camelot.core.utils import ugettext as _
     61          filename = unicode(QtGui.QFileDialog.getSaveFileName(None, _("Save File"),))
     62

     63          def create_po_exporter(filename, collection_getter):
     64

     65              def po_exporter():
     66                  file = open(filename, 'w')
     67                  for translation in collection_getter():
     68                      file.write( (u'msgid  "%s"\n'%translation.source).encode('utf-8') )
     69                      file.write( (u'msgstr "%s"\n\n'%translation.value).encode('utf-8') )
     70

     71              return po_exporter
     72

     73          post(create_po_exporter(filename, collection_getter))
     74

     75 -class Translation( Entity ):
     76      using_options( tablename = 'translation' )
     77      language = Field( camelot.types.Language, index = True )
     78      source = Field( Unicode( 500 ), index = True )
     79      value = Field( Unicode( 500 ) )
     80      cid = Field( INT(), default = 0, index = True )
     81      uid = Field( INT(), default = 0, index = True )
     82

     83      # cache, to prevent too much of the same sql queries

     84      _cache = dict()
     85

     86 -    class Admin( EntityAdmin ):
     87          verbose_name_plural = _( 'Translations' )
     88          form_size = ( 700, 150 )
     89          section = 'configuration'
     90          list_display = ['source', 'language', 'value', 'uid']
     91          list_filter = ['language']
     92          list_actions = [ExportAsPO()]
     93

     94      @classmethod
     95 -    def translate( cls, source, language ):
     96          """Translate source to language, return None if no translation is found"""
     97          if source:
     98              key = ( source, language )
     99              if key in cls._cache:
    100                  return cls._cache[key]
    101              translation = cls.query.filter_by( source = unicode( source ), language = language ).filter( Translation.uid != 0 ).first()
    102              if translation:
    103                  cls._cache[key] = translation.value
    104                  return translation.value
    105              return None
    106          return ''
    107

    108      @classmethod
    109 -    def translate_or_register( cls, source, language ):
    110          """Translate source to language, if no translation is found, register the

    111          source as to be translated and return the source"""
    112          if source:
    113              source = unicode( source )
    114              translation = cls.translate( source, language )
    115              if not translation:
    116                  if not cls.query.filter_by( source = source, language = language ).first():
    117                      if ( source, language ) not in cls._cache:
    118                          from elixir import session
    119                          registered_translation = Translation( source = source, language = language )
    120                          cls._cache[( source, language )] = source
    121                          session.flush( [registered_translation] )
    122                          logger.debug( 'registed %s with id %s' % ( source, registered_translation.id ) )
    123                  return source
    124              return translation
    125          return ''
    126