15,534
edits
Changes
→Textual reports
Coding guidelines to enable easy and correct translation of strings on the User Interface.
==Introduction==
http://gramps-project.org/2006/04/looking-back-over-5-years).
Therefore, all strings meant
for the user should always be flagged for translation.
In order to be considered for inclusion in the offical GRAMPS Gramps release, any piece of code must support internationalization. What this means is that the Python module must support [[Translating GRAMPSGramps|translations]] into different languages. GRAMPS Gramps provides support to make this as easy as possible for the developer. For enabling, a language code must be set on the ''configure.in'' file into ''[[Template:Gramps_translations#ALL_LINGUAS |ALL_LINGUAS]]'' section.
==How to allow translations==
Example 1:
print _("Hello world!")
In this example, GRAMPS Gramps will attempt to translate the string. If a translation exists, the call to the function will return the translation. If a translation does not exist, the original string is returned. === More complicated translations === In addition to <tt>gettext</tt>, GrampsTranslation offers two more specialized retrieval functions, <tt>ngettext</tt> and <tt>sgettext</tt>. In some strings, it's necessary to specify different translations depending upon the number of an argument. For example, George Smith and Annie Jones have 1 child George Smith and Annie Jones have 3 children We'd code that in python as follows: _ = glocale.translation.ngettext _(George Smith and Annie Jones have %(num)d child, George Smith and Annie Jones have %(num)d children, n) % {num : n} In other cases, it's necessary to provide a hint to translators, e.g. _(Remaining names | rest) We're making sure that the translators know that this message id means "what's left" rather than "take a nap". When the file is translated, this is no problem, because the translation doesn't include the hint -- but if the user is working in English, we don't want him to see the hint, so we need to alias _ to sgettext: _ = glocale.translation.sgettext Often you need to combine them. While <tt>ngettext</tt> and <tt>sgettext</tt> can each handle plain strings, neither can handle the other's strings. Fortunately the <tt>intltool</tt> message extractor is pretty stupid, so any function name that ends in either <tt>_</tt> or <tt>gettext</tt> will work. This will work pretty well: _ = glocale.translation.gettext N_ = glocale.translation.ngettext S_ = glocale.translation.sgettext Obviously you would pass the translatable string to the right function. === Encoding ===String handling can be a bit tricky in a localized environment so it's important that developers understand Unicode string handling in both versions of the language. This is mostly a problem for Microsoft Windows™: Mac OSX and Linux use UTF8 for just about everything if the locale is set up correctly (and we try to do that when Gramps starts up), so one can get away with a lot of encoding mistakes on those platforms. Windows™ on the other hand uses a slightly modified version of UTF16 for file names and retains the old DOS [http://en.wikipedia.org/wiki/Code_page code page] system for encoding output to cmd.exe. The take-away is that if you need to mess with input or output encoding, be sure to test on both Linux and Windows before deciding that you're done. If you're not set up for multiple-platform testing arrange with someone,, who can test for you on the platform you don't have. ====Python 2====Python 2.7 has two text classes, <tt>[https://docs.python.org/2.7/library/functions.html#str str]</tt> and <tt>[https://docs.python.org/2.7/library/functions.html#unicode unicode]</tt>. <tt>Unicode</tt> objects are encoded in UTF16 internally on most platforms, and most python '''output''' functions will do the right thing with them. One caveat here: passing both <tt>unicodes</tt> and <tt>strs</tt> to <tt>os.path.join()</tt> will return a <tt>str</tt>, so either make sure when constructing a path that all arguments are <tt>unicodes</tt> or convert the result.
By default string constants in Python 2 are <tt>str</tt>.
===Into glade =Python 3====Python 3 also provides two test classes, <tt>[https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str str]</tt> and <tt>[https://docs.python.org/3/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview bytes]</tt>. In Python 3, <tt>str</tt> is the unicode type and <tt>bytes</tt> is text encoded some other way. Everything pretty much "just works". ====Portability Functions and constants====We've provided a couple of functions in gramps/gen/constfunc.py to ease conversion of <tt>strs</tt> to <tt>unicodes</tt>; these include the necessary tests to portably do the right thing regardless of what's passed to them and according to which version of Python is in use:* <tt>cuni</tt> is an alias for [https://docs.python.org/2.7/library/functions.html#unicode unicode] in Python 2 and for [https://docs.python.org/3/library/functions.html#func-str str] in Python 3. This has no protective checks so use it with care.* <tt>conv_to_unicode(string, encoding='utf8')</tt>: This ensures that its return value is a Unicode string which has been converted from a non-Unicode in the <tt>encoding</tt>, which defaults to UTF8 for ease of use with the GUI.* <tt>get_env_var(string, default=None)</tt>: On Windows™ in Python2, uses the <tt>ctypes</tt> module to invoke the Microsoft Unicode API to read the value of an environment variable and return a Unicode; otherwise returns the value from the <tt>os.environ</tt> array.There are also two constants:* <tt>STRTYPE</tt> is an alias for [https://docs.python.org/2.7/library/functions.html#basestring basestring] in Python 2 and for [https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str str] in Python 3. It can be used to test whether an object is a text-type.* <tt>UNITYPE</tt> is an alias for [https://docs.python.org/2.7/library/functions.html#unicode unicode] in Python 2 and for [https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str str] in Python 3. It can be used to test whether an object is already encoded in Unicode. ====For portable string handling on all platforms and for all locales====* Localized strings returned from gettext, ngettext, etc. are always unicode* Text files should always be encoded in UTF8. The easy and portable way to do this is to:*: <pre>import io</pre>*: <pre>fh = io.open(filepath, mode, encoding='utf8')</pre>*: where ''mode'' is one of r, rw, r+, or w+. ''Don't open these files in binary mode!'' Pass unicode-type strings to fh.write() and expect the same from fh.read().* Always read environment variables with <tt>constfuncs.get_env_var()</tt> if there's any chance that it will contain a non-ASCII character.* Use <tt>from __future__ import unicode_literals</tt> in any source filewhich might present strings to the user or to the operating system.*:When creating string literals, '''don't do this:'''*:<pre>print _(u"Eg, valid values are 12.0154, 50° 52′ 21.92″N")</pre>*:Because the <tt>u</tt> prefix was removed for Python 3.0-3.2. (It was restored in 3.3 for compatibility with 2.7, but it's not necessary.)*:Instead, put in the first line of the module*:<pre># *-* coding: utf-8 *-*</pre>*:then in the imports section*:<pre>from __future__ import unicode_literals</pre>*:which makes all of the literals unicode. '''Make sure that your editor is set up to save utf-8!''' ===Glade files===
Just enable the translatable attribute on an XML element.
<property name="label" translatable="no"><b> - </b> </property>
If you plan to use non ASCII characters in a string, that shall be translated,
do not use escape sequences:
Eg, valid values are 12.0154, 50<code>&</code>#xB0; 52' 21.92"N
use in steadinstead:
Eg, valid values are 12.0154, 50° 52′ 21.92″N
In this case note the special unicode characters for deg, min, sec.'''Ensure that your editor is set up to encode the characters in UTF-8!'''
====Accessibility====
See [http://www.gnu.org/software/gettext/manual/gettext.html GNU gettext] and [http://live.gnome.org/TranslationProject/DevGuidelines/Localize%20using%20gettext%20and%20intltool Gnome] provide utilities and a [http://www.gnome.org/~malcolm/i18n/build-changes.html translation framework] (''previously [http://gramps.svn.sourceforge.net/viewvc/gramps/branches/maintenance/gramps20/gramps2/src/build_po build_po] and [http://gramps.svn.sourceforge.net/viewvc/gramps/branches/maintenance/gramps20/gramps2/src/get_strings get_stringsAddons_Development#Localization|Addons development]''):* [http://www.gnu.org/software/autoconf/manual/gettext/msginit-Invocation.html msginit] will generate a standard gettext header.* intltool-update will manage template and translations.* intltool-extract will extract translation strings on ''.glade'' and ''.xml'' files, by generating files with ''.h'' extensionfor more details.
===Files and directory===
Translators use a generic file <code>gramps.pot</code> to generate their <code>.po</code> file.
Note that because strings are extracted by a script from the source file, string constants and not variables must be enclosed in the <code>_()</code> call. In the following example, the extraction script will not extract the string.
At run time, the <code>_()</code> calls will translate the string by looking it up in the translation database (created from the <code>.po</code> files) and returning the translated string.
==Tips for writing a translatable Python module==
===Use complete sentences===
Don't build up a sentence from phrases. Because a sentence is ordered in a particular way in your language does not mean that it is ordered the same way in another. Providing the entire sentence as a single unit allows the translator to make a meaningful translation. Do not concatenate phrases or terms as they will then show up as separate phrases or terms to be translated and the complete sentence may then show up incorrectly, especially in right-to-left languages (Arabic, Hebrew, etc.).
===Use named %s /%d values===
Python provides a powerful mechanism that allows the reordering of %s values in a string. A translator may need to rearrange the structure of a sentence, and it may not match the order you chose. For example:
print "%s was born in %s" % ('Joe','Toronto')
'city' : 'Toronto', 'male_name' : 'Joe'}
In this case, the order of the %s formatters is not important, since the values will be looked up in the dictionary at run time to resolve the value. The translator can reorder the %s formatters, or even remove them without causing any problems.
Note that Python also allows a variation which some people find easier to read:
print "%(male_name)s was born in %(city)s" % dict(
city = 'Toronto', male_name = 'Joe')
Some languages are using right-to-left text direction. It is important to use named arguments when there is more than one %s/%d value into a translation string.
===Provide separate strings for masculine and feminine.===
Plurals are handled differently in various languages. Whilst English or German have a singular and a plural form, other languages like Turkish don't distinguish between plural or singular and there are languages which use different plurals for different numbers, e.g. Polish.
Gramps provides a [[Translating_GRAMPSTranslating_Gramps#Plural_forms|plural forms]] support, useful for locales with multiples plurals according to a number (''often slavic based languages'') or for Asian family languages (''singular = plural'').
Note, some locales need singular form with [http://en.wikipedia.org/wiki/Plural#Zero zero] and plural form might be also used in this case.
We need to call module :
from TransUtils gen.ggettext import sgettext as _
or
from TransUtils gen.ggettext import sngettext as _(if you use ngettext)# not implemented
Translation string will use context, but this will be hidden on user interface.
See ''the person'' details # or See ''the family, the event, etc...'' details
Make ''the person'' active
===Genitive form===
Genitive (and some other) forms need to modify the name itself into some locales, like Finnish or Swedish.
Instead of "free form" text that talks about
e.g.
son '''of %s'''
better would be for example some tabulated format like this:
son: %s
daughter: %s
which doesn't require genitive.
===Punctuation===
Use of commas, semicolons and spacing can be different than into english.
''todo''
==Changing translated text message in the source code==
One of the severities in our bug tracker is "text", which ranks up as easier than "tweak" and "minor", but more difficult than "trivial". If a bug is concerned with readability or correctness of a text that Gramps outputs, whether in GUI, in a console error message, or in a produced report, then "text" is the severity to use. So why is it more than "trivial"?
As described above, any translated text in the source code gets reflected into tens of *.po files, maintained by the translators. So every time you just change it in the source, ALL the translators need to do the translation again. Normally, the translation environment will give a prudent suggestion, but there is still a manual approval step. If you check in the change, the string will not be translated until the translators pick it up.
This is why, if what you change is just a couple of spelling mistakes, a missing comma in the middle, or maybe an extra space somewhere in the message, it's a good idea to save the translators' work, by doing a global search and replace of your source message text in the *.po files, and committing these along with your change.
For short enough messages, that don't span multiple lines in the *po files, you can do it by executing
perl -pi -e 's/YOUR MESSAGE BEFORE CORRECTION/your message after correction/g;' *.po *.pot
in the po/ directory. Make sure you do a "git diff" and observe the results make sense. (You'll probably have to escape some characters in the regular expression, such as | or .).
To make it easier to port your changes across multiple branches, it's a good idea to separate the changes in the source tree from the po/ ones. This way, you'll be able to quickly re-apply the source changes using normal cross-branch porting workflow (such as `git cherry-pick'), and then adjust and re-run the search-and-replace in the po/ on the new branch, because, most likely, it won't reapply due to the differences in the .po layout.
{{man note| Note |To stress it again, only do it for text change that didn't change how it is going to be translated. If you'd like your change to be somehow reflected in the translations, let the translators do the work instead.}}
==Textual reports==
Since Gramps-3.2 we are able to select the language for textual reports, see [http://www.gramps-project.org/bugs/view.php?id=feature {{bug|2371 this feature]}}.
For providing this option:
self.__get_date(event.get_date_object())
self.__get_type(event.get_type())
[[Category:Translators/Categories]]
[[Category:Developers/Tutorials]]
[[Category:Developers/General]]
[[Category:Addons]]