Differences
This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
wiki:documentation:devguide:core:translator [2016/10/03 10:27] carolina.santos [C++] |
wiki:documentation:devguide:core:translator [2016/11/04 07:32] (current) carolina.santos [CMake] |
||
---|---|---|---|
Line 1: | Line 1: | ||
====== TerraLib.Core: Translator ====== | ====== TerraLib.Core: Translator ====== | ||
- | A classe **te::core::Translator** fornece suporte a tradução de idiomas utilizando a [[http://www.boost.org/doc/libs/1_62_0/libs/locale/doc/html/index.html | Boost.Locale]]. | + | The class **te::core::Translator** provides support for language translation using [[http://www.boost.org/doc/libs/1_62_0/libs/locale/doc/html/index.html | Boost.Locale]]. |
- | Esta classe é um //singleton// que pode ser utilizado para traduzir mensagens de acordo com a região do sistema e dicionários de traduções. | + | This class is a //singleton// that can be used to translate messages according to the system locale and translation dictionaries. |
- | Os dicionários de traduções são conjuntos de arquivos textuais e binários que são criados através das ferramentas [[https://www.gnu.org/software/gettext/ | GNU Gettext]]. | + | Translation dictionaries are sets of textual and binary files that are created through the [[https://www.gnu.org/software/gettext/ | GNU Gettext]] tools. |
- | + | ||
- | A tradução não é automática, sendo necessário realizar este processo manualmente nos arquivos ".po". | + | |
+ | The translation is not automatic, it is necessary to perform this process manually in the "po" files. | ||
===== API ===== | ===== API ===== | ||
==== C++ ==== | ==== C++ ==== | ||
- | A API para tradução de mensagens na TerraLib é definida pela classe ''Translator'', mostrada abaixo: | + | The API for messages translation in TerraLib is defined by **Translator** class, shown below: |
<code cpp> | <code cpp> | ||
- | class TECOREEXPORT Translator | + | namespace te |
{ | { | ||
- | public: | + | namespace core |
+ | { | ||
+ | /*! | ||
+ | \class Translator | ||
+ | |||
+ | \brief This singleton is designed to deal with multi-language text translation in TerraLib. | ||
+ | */ | ||
+ | class Translator | ||
+ | { | ||
+ | |||
+ | public: | ||
+ | |||
+ | static Translator& instance(); | ||
- | static Translator& getInstance(); | + | /*! |
+ | \brief It tries to translate the specified text string. | ||
- | /*! | + | If no translation is available it will return the |
- | \brief It tries to translate the specified text string. | + | original message (always in English). |
- | If no translation is available it will return the | + | \param message The text to be translated. |
- | original message (always in English). | + | |
- | \param message The text to be translated. | + | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. |
- | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. | + | \note The returned message is UTF-8 encoded. |
+ | */ | ||
+ | std::string translate(const std::string& message); | ||
- | \note The returned message is UTF-8 encoded. | + | /*! |
- | */ | + | \brief It tries to translate the specified text string. |
- | std::string translate(const std::string& message); | + | |
- | /*! | + | If no translation is available it will return the |
- | \brief It tries to translate the specified text string. | + | original message (always in English). |
- | If no translation is available it will return the | + | \param message The text to be translated. |
- | original message (always in English). | + | |
- | \param message The text to be translated. | + | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. |
- | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. | + | \note The returned message is UTF-8 encoded. |
+ | */ | ||
+ | std::string translate(const char* message); | ||
- | \note The returned message is UTF-8 encoded. | + | /*! |
- | */ | + | \brief It tries to translate the specified text string accounting for plural forms. |
- | std::string translate(const char* message); | + | |
- | /*! | + | If no translation is available it will return the |
- | \brief It tries to translate the specified text string accounting for plural forms. | + | original message (always in English). |
- | If no translation is available it will return the | + | \param msg1 The singular form of the text to be translated. |
- | original message (always in English). | + | \param msg2 The plural form of the text to be translated. |
+ | \param n This parameter is used to determine the plural form. | ||
- | \param msg1 The singular form of the text to be translated. | + | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. |
- | \param msg2 The plural form of the text to be translated. | + | |
- | \param n This parameter is used to determine the plural form. | + | |
- | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. | + | \note The returned message is UTF-8 encoded. |
+ | */ | ||
+ | std::string translate(const std::string& msg1, | ||
+ | const std::string& msg2, | ||
+ | unsigned int n); | ||
- | \note The returned message is UTF-8 encoded. | + | /*! |
- | */ | + | \brief It tries to translate the specified text string accounting for plural forms. |
- | std::string translate(const std::string& msg1, | + | |
- | const std::string& msg2, | + | |
- | unsigned int n); | + | |
- | /*! | + | If no translation is available it will return the |
- | \brief It tries to translate the specified text string accounting for plural forms. | + | original message (always in English). |
- | If no translation is available it will return the | + | \param msg1 The singular form of the text to be translated. |
- | original message (always in English). | + | \param msg2 The plural form of the text to be translated. |
+ | \param n This parameter is used to determine the plural form. | ||
- | \param msg1 The singular form of the text to be translated. | + | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. |
- | \param msg2 The plural form of the text to be translated. | + | |
- | \param n This parameter is used to determine the plural form. | + | |
- | \return A string of the translated message. You must not delete the memory pointed by the returned pointer. | + | \note The returned message is UTF-8 encoded. |
+ | */ | ||
+ | std::string translate(const char* msg1, | ||
+ | const char* msg2, | ||
+ | unsigned int n); | ||
- | \note The returned message is UTF-8 encoded. | + | /*! |
- | */ | + | \brief It sets the locale for the Translator. |
- | std::string translate(const char* msg1, | + | |
- | const char* msg2, | + | |
- | unsigned int n); | + | |
- | /*! | + | \param locale A string of the new locale. |
- | \brief It sets the locale for the Translator. | + | */ |
+ | void setLocale(const std::string &locale); | ||
- | \param locale A string of the new locale. | + | /*! |
- | */ | + | \brief It adds a new text domain (text catalog). |
- | void setLocale(const std::string &locale); | + | |
- | /*! | + | \param textDomain A given message domain (just a name). A text domain is the name of the catalog used to translate the message. |
- | \brief It adds a new text domain (text catalog). | + | |
- | \param textDomain A given message domain (just a name). A text domain is the name of the catalog used to translate the message. | + | \param dir Where the text domain is located. |
- | \param dir Where the text domain is located. | + | \exception Exception If the text domain already exists it raises an exception. If you are not sure about the existence of a text domain, use the exist() method. |
+ | */ | ||
+ | void addTextDomain(const std::string& textDomain, const std::string& dir); | ||
- | \exception Exception If the text domain already exists it raises an exception. If you are not sure about the existence of a text domain, use the exist() method. | ||
- | */ | ||
- | void addTextDomain(const std::string& textDomain, const std::string& dir); | ||
+ | /*! | ||
+ | \brief It returns true if the text domain (text catalog) exists and false otherwise. | ||
- | /*! | + | \param textDomain A given message domain (just a name). |
- | \brief It returns true if the text domain (text catalog) exists and false otherwise. | + | */ |
+ | bool exist(const std::string& textDomain); | ||
+ | }; | ||
- | \param textDomain A given message domain (just a name). | + | } // end namespace core |
- | */ | + | } // end namespace te |
- | bool exist(const std::string& textDomain); | + | |
- | }; | + | |
</code> | </code> | ||
- | Além da classe acima, existem macros que auxiliam no processo de uso da API. | + | In addition to the class above, there are macros that assist in API usage process. |
- | A macro **TE_ADD_TEXT_DOMAIN** irá registrar o nome de um arquivo de tradução no sistema de idiomas e onde ele está localizado: | + | The macro **TO ADD TEXT DOMAIN** will register the name of a translation file in the language system and where it is located: |
<code cpp> | <code cpp> | ||
Line 122: | Line 134: | ||
</code> | </code> | ||
- | A macro **TE_TR** pode ser utilizada para delimitar os textos que devam ser traduzidos: | + | The macro **TE_TR** can be used to delimit text that should be translated: |
<code cpp> | <code cpp> | ||
Line 128: | Line 140: | ||
</code> | </code> | ||
- | Quando as mensagens dependem da flexão gramatical de número (plural), deve-se utilizar a macro **TE_TR_PLURAL**: | + | When messages depend on the number of inflexion (plural), you should use the macro **TE_TR_PLURAL**: |
<code cpp> | <code cpp> | ||
Line 135: | Line 147: | ||
</code> | </code> | ||
- | A macro **TE_TR_LANGUAGE** só deve ser utilizada pela aplicação para informar qual o idioma em uso: | + | The macro **TE_TR_LANGUAGE** should only be used by the application to inform which language is in use: |
<code cpp> | <code cpp> | ||
Line 144: | Line 156: | ||
==== CMake ==== | ==== CMake ==== | ||
- | Para facilitar a criação de arquivos binários contendo as mensagens traduzidas, bem como sua inclusão nos pacotes de distribuição binária dos aplicativos da família TerraLib, foi criada uma macro no CMake chamada **TERRALIB_REGISTER_TRANSLATION** capaz de automatizar esse processo. Esta macro encontra-se no arquivo //build/cmake/terralib_macros.cmake// do repositório de código. | + | To facilitate the creation of binary files containing the translated messages as well as their inclusion in the binary distribution of packages in TerraLib family applications, the macro **TERRALIB_REGISTER_TRANSLATION** was created in CMake to be able to automate this process. This macro is in //build/cmake/terralib_macros.cmake// file in the code repository. |
- | Todas as bibliotecas da TerraLib que necessitarem do sistema de tradução de mensagens deverão usar a macro acima em seus arquivos de projeto de build (//CMakeLists.txt//). Ela possui a seguinte forma: | + | All TerraLib libraries that need the message translation system should use the above macro in their build project files (//CMakeLists.txt//), in the following form: |
<code cpp> | <code cpp> | ||
- | TERRALIB_REGISTER_TRANSLATION("nome-biblioteca" "idioma" "diretório-arquivo-po" "diretório-saída-arquivo-mo") | + | TERRALIB_REGISTER_TRANSLATION("library-name" "language" "po-file-directory" "mo-file-output-directory") |
</code> | </code> | ||
- | Onde: | + | Where: |
- | * ''nome-biblioteca'': nome da biblioteca ou executável definido como target no script CMake. Ex: terralib_mod_core | + | * ''library-name'': library name or executable set to target in CMake script. Ex: terralib_mod_core |
- | * ''idioma'': região que se encontram as traduções. Ex: pt_BR | + | * ''language'': region of translations. Ex: pt_BR |
- | * ''diretório-arquivo-po'': pasta onde se encontra o arquivo de traduções. O arquivo nesta pasta deve obedecer a seguinte regra de formação: //nome_da_biblioteca_idioma//. Ex: terralib_mod_core_pt_BR.po | + | * ''po-file-directory'': folder of the translation file. The file in this folder must meet the following formation rule: //library_name_language//. Ex: terralib_mod_core_pt_BR.po |
- | * ''diretório-saída-arquivo-mo'': pasta de saída para o arquivo binário gerado a partir do arquivo contendo as traduções. De preferência, utilize uma pasta na árvore de build do projeto CMake. Ex: ${CMAKE_BINARY_DIR}/share/terralib/translations | + | * ''mo-file-output-directory'': output folder to the binary file generated from the file containing the translations. Preferably, use a folder in the build tree of CMake project. Ex: ${CMAKE_BINARY_DIR}/share/terralib/translations |
- | Como exemplo, vamos tomar a linha do arquivo //CMakeLists.txt// do projeto da biblioteca TerraLib.Core: | + | As an example, we can take the line of //CMakeLists.txt// file of the TerraLib.Core project library: |
<code cpp> | <code cpp> | ||
Line 168: | Line 180: | ||
- | ===== Exemplos ===== | + | ===== Examples ===== |
- | Os arquivos ".po" podem ser criados na linha de comando com as ferramentas da [[https://www.gnu.org/software/gettext/ | GNU Gettext]] ou através de ferramentas gráficas como o [[https://poeditor.com/ | POEditor]] ou o [[https://poedit.net/download | Poedit]]. | + | The files ".po" can be created from the command line with the tools of [[https://www.gnu.org/software/gettext/ | GNU Gettext]] or through graphical tools like [[https://poeditor.com/ | POEditor]] or [[https://poedit.net/download | Poedit]]. |
- | A seguir, iremos mostrar como criar esses arquivos na linha de comando com as ferramentas da [[https://www.gnu.org/software/gettext/ | GNU Gettext]]. | + | Next, we will show how to create these files on the command line with [[https://www.gnu.org/software/gettext/ | GNU Gettext]] tools. |
- | Para começar um novo arquivo de tradução, primeiramente, temos que criar um arquivo com a extensão ".pot", que conterá um template das mensagens identificadas no código fonte. O comando a seguir mostra como extrair as mensagens dos arquivos informados: | + | To start a new translation file, first we have to create a file with the extension ".pot", which contains a template of the messages identified in the source code. The following command shows how to extract messages from the reported files: |
<code cpp> | <code cpp> | ||
Line 180: | Line 192: | ||
</code> | </code> | ||
- | O comando acima irá produzir o arquivo //terralib_unittest_core.pot//. | + | The above command will produce the file //terralib_unittest_core.pot//. |
- | Caso você ainda não tenha um arquivo com a extensão ".po", no caso da criação de novas bibliotecas, utilize o comando abaixo para criar este arquivo onde deverão ser incluídas as traduções para um determinado idioma: | + | If you do not already have a file with the extension ".po" in the case of creating new libraries, use the following command to create this file where should be included the translations for a particular language: |
<code cpp> | <code cpp> | ||
Line 188: | Line 200: | ||
</code> | </code> | ||
- | O comando acima irá produzir o arquivo //terralib_unittest_core_pt_BR.po//. | + | The above command will produce the file //terralib_unittest_core_pt_BR.po//. |
- | Caso você já possua um arquivo ".po" e deseje apenas realizar uma atualização do mesmo, você pode fazer isso através do seguinte comando: | + | If you already have a file ".po" and just want to perform an update, you can do this using the following command: |
<code cpp> | <code cpp> | ||
Line 198: | Line 210: | ||
</code> | </code> | ||
- | **Nota:** No comando xgettext, onde você está atualizando o arquivo template, você pode informar novos arquivos se necessário. | + | **Note:** In xgettext command where you are upgrading the template file, you can enter new files if necessary. |
- | A criação dos arquivo binários com a extensão ".mo", contendo as traduções para uso nos sistemas, é feita de forma automática no build através da macro **TERRALIB_REGISTER_TRANSLATION**. Para isso, acrescente no seu //CMakeLists.txt// o registro de traduções como mostrado abaixo: | + | The creation of the binary files with the extension ".mo", containing translations to use in the systems, is done automatically in the build through the macro **TERRALIB_REGISTER_TRANSLATION**. Add to your //CMakeLists.txt// the record of translations as shown below: |
<code cpp> | <code cpp> | ||
Line 208: | Line 220: | ||
</code> | </code> | ||
- | **Nota:** utilizar o mesmo nome da biblioteca ou executável no registro de sua tradução. | + | **Note:** use the same name as the library or executable in the record of your translation. |
- | No seu código fonte inclua uma chamada à macro **TE_ADD_TEXT_DOMAIN** para adicionar em tempo de execução o seu arquivo de tradução. Veja o exemplo abaixo: | + | In your source code include a call to the macro **TE_ADD_TEXT_DOMAIN** to add at runtime your translation file. See the example below: |
<code cpp> | <code cpp> | ||
Line 232: | Line 244: | ||
</code> | </code> | ||
- | Uma vez que o arquivo de tradução encontra-se carregado, as macros **TE_TR** e **TE_TR_PLURAL** irão produzir a tradução correta: | + | Once the translation file is loaded, macros **TE_TR** and **TE_TR_PLURAL** will produce the correct translation: |
<code cpp> | <code cpp> | ||
Line 263: | Line 275: | ||
- | ===== Referências ===== | + | ===== Additional References ===== |
* [[http://www.boost.org/doc/libs/1_56_0/libs/locale/doc/html/messages_formatting.html | Boost.Locale - Messages Formatting (Translation)]] | * [[http://www.boost.org/doc/libs/1_56_0/libs/locale/doc/html/messages_formatting.html | Boost.Locale - Messages Formatting (Translation)]] |