Servicio ScriptForge.L10N

Este servicio proporciona una serie de métodos relacionados con la traducción de cadenas con un impacto mínimo en el código fuente del programa. Los métodos proporcionados por el servicio L10N pueden utilizarse principalmente para:

note

The acronym L10N stands for Localization and refers to a set of procedures for translating software to a specific country or region.


PO files have long been promoted in the free software community as a means to providing multilingual user interfaces. This is accomplished through the use of human-readable text files with a well defined structure that specifies, for any given language, the source language string and the localized string.

The main advantage of the PO format is dissociation of the programmer and the translator. PO files are independent text files, so the programmer can send POT template files to translators, who will then translate their contents and return the translated PO files for each supported language.

tip

El servicio L10N se basa en la implementación de GNU de los archivos PO (objeto portátil). Para conocer más de este formato de archivo, visite la documentación de utilidades de GNU gettext: archivos PO (en inglés).


Este servicio implementa los métodos que se enumeran a continuación:

note

Note that the first two methods are used to build a set of translatable strings and export them to a POT file. However, it is not mandatory to create POT files using these methods. Since they are text files, the programmer could have created them using any text editor.


Invocación del servicio

Antes de utilizar el servicio L10N, es necesario cargar o importar la biblioteca ScriptForge:

note

• Para cargar la biblioteca ScriptForge que necesitan las macros de Basic se debe usar la siguiente declaración:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Los scripts de Python necesitan importar el módulo scriptforge:
from scriptforge import CreateScriptService


There are several ways to invoke the L10N service using up to five optional arguments that specify the folder where PO files are stored, the locale and encoding to be used, as well as a fallback PO file and its encoding.

Sintaxis:

CreateScriptService("L10N", opt foldername: str, opt locale: str, encoding: str = "UTF-8", opt locale2: str, encoding2: str = "UTF-8"): svc

foldername: The folder containing the PO files. It must be expressed in the FileSystem.FileNaming notation.

locale: A string in the form "la-CO" (language-COUNTRY) or in the form "la" (language) only.

encoding: The character set to be used. The default encoding is "UTF-8".

locale2: A string specifying the fallback locale to be used in case the PO file corresponding to the locale defined the locale parameter does not exist. This parameter is expressed in the form "la-CO" (language-COUNTRY) or "la" (language) only.

encoding2: The character set of the fallback PO file corresponding to the locale2 argument. The default encoding is "UTF-8".

note

To learn more about the names of character sets, visit IANA's Character Set page. Beware that LibreOffice does not implement all existing character sets.


Ejemplo:

En BASIC

The following example instantiates the L10N service without any optional arguments. This will only enable the AddText and ExportToPOTFile methods, which is useful for creating POT files.


      GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
      Dim myPO As Variant
      Set myPO = CreateScriptService("L10N")
    

The example below specifies the folder containing the PO files. Because the locale is not defined, the service instance will use the locale defined for the LibreOffice user interface, which is the same locale defined in the OfficeLocale property of the Platform service.


      Set myPO = CreateScriptService("L10N", "C:\myPOFiles")
    
warning

The example above will result in an runtime error if the PO file corresponding to the OfficeLocale locale does not exist in the specified folder.


In the example below, the locale is explicitly defined to be Belgian French ("fr-BE"), hence the service will load the file "fr-BE.po" from the folder "C:\myPOFiles". If the file does not exist, an error will occur.


      Set myPO = CreateScriptService("L10N", "C:\myPOFiles", "fr-BE", "UTF-8")
    

To avoid errors, it is possible to specify a preferred and a fallback locale and encoding. The following example will first try to load the file "fr-BE.po" from the specified folder and if it does not exist, the file "en-US.po" will be loaded.


      Set myPO = CreateScriptService("L10N", "C:\myPOFiles", "fr-BE", "UTF-8", "en-US", "UTF-8")
    
Icono de consejo

PO files must be named in the form "la-CO.po" or "la.po", where "la" refers to the language and "CO" is the country. Some examples are: "en-US.po", "fr-BE.po" or "fr.po".


Es recomendable liberar recursos después del uso:


      Set myPO = myPO.Dispose()
    
En Python

Los ejemplos anteriores pueden expresarse en Python de la siguiente manera:


      from scriptforge import CreateScriptService
      myPO = CreateScriptService('L10N')
    

      myPO = CreateScriptService('L10N', r'C:\myPOFiles')
    

      myPO = CreateScriptService('L10N', r'C:\myPOFiles', 'fr-BE')
    

      myPO = CreateScriptService('L10N', r'C:\myPOFiles', 'fr-BE', 'UTF-8', 'en-US', 'UTF-8')
      myPO = myPO.Dispose()
    
note

Several instances of the L10N service may coexist. However, each instance must use a separate directory for its PO files.


Propiedades

Nombre

De solo lectura

Tipo

Descripción

Folder

String

The folder containing the PO files (see the FileSystem.FileNaming property to learn about the notation used).

Languages

Array

A zero-based array listing all the base names (without the ".po" extension) of the PO-files found in the specified Folder.

Locale

String

The currently active language-COUNTRY combination. This property will be initially empty if the service was instantiated without any of the optional arguments.


Lista de métodos en el servicio L10N

AddText
AddTextsFromDialog

ExportToPOTFile

GetText


AddText

Añade una entrada nueva en la lista de cadenas regionalizables. No debe existir aún.

The method returns True if successful.

Sintaxis:

svc.AddText(context: str = '', msgid: str = '', comment: str = ''): bool

Parámetros:

context: The key to retrieve the translated string with the GetText method. This parameter has a default value of "".

msgid: The untranslated string, which is the text appearing in the program code. It must not be empty. The msgid becomes the key to retrieve the translated string via GetText method when context is empty.

The msgid string may contain any number of placeholders (%1 %2 %3 ...) for dynamically modifying the string at runtime.

comment: Optional comment to be added alongside the string to help translators.

Ejemplo:

El ejemplo a continuación crea un conjunto de cadenas en inglés:

En BASIC

      myPO.AddText(, "This is a string to be included in a POT file")
      myPO.AddText("CTX1", "A string with a context")
      myPO.AddText(, "Provide a String value", Comment := "Do not translate the word String")
    
En Python

      myPO.AddText(msgid = 'This is a string to be included in a POT file')
      myPO.AddText('CTX1', 'A string with a context')
      myPO.AddText(msgid = 'Provide a String value', comment = 'Do not translate the word String')
    

AddTextsFromDialog

Automatically extracts strings from a dialog and adds them to the list of localizable text strings. The following strings are extracted:

The method returns True if successful.

note

The dialog from which strings will be extracted must not be open when the method is called.


When a L10N service instance is created from an existing PO file, use the GetTextsFromL10N method from the Dialog service to automatically load all translated strings into the dialog.

Sintaxis:

svc.AddTextsFromDialog(dialog: svc): bool

Parámetros:

dialog: a Dialog service instance corresponding to the dialog from which strings will be extracted.

Ejemplo:

The following example extracts all strings from the dialog "MyDialog" stored in the "Standard" library and exports them to a POT file:

En BASIC

      oDlg = CreateScriptService("Dialog", "GlobalScope", "Standard", "MyDialog")
      myPO = CreateScriptService("L10N")
      myPO.AddTextsFromDialog(oDlg)
      myPO.ExportToPOTFile("en-US.pot")
    
En Python

      dlg = CreateScriptService("Dialog", "GlobalScope", "Standard", "Dialog1")
      myPO = CreateScriptService("L10N")
      myPO.AddTextsFromDialog(dlg)
      myPO.ExportToPOTFile("en-US.pot")
    

ExportToPOTFile

Exporta un conjunto de cadenas no traducidas en un archivo POT.

To build a set of strings you can use either a succession of AddText method calls, or by a successful invocation of the L10N service with the foldername argument present. It is also possible to use a combination of both techniques.

The method returns True if successful.

Sintaxis:

svc.ExportToPOTFile(filename: str, header: str = '', encoding:str = 'UTF-8'): bool

Parámetros:

filename: The output file in FileSystem.FileNaming notation.

header: Comments that will be added on top of the generated POT file.

Do not include any leading "#" characters. If you want the header to be broken into multiple lines, insert escape sequences (\n) where relevant. A standard header will be added alongside the text specified in the header argument.

encoding: The character set to be used (Default = "UTF-8").

Ejemplo:


       ' Basic
       myPO.ExportToPOTFile("myFile.pot", Header := "First line of the header\nSecond line of the header")
    

      # Python
      myPO.ExportToPOTFile('myFile.pot', header = 'First line of the header\nSecond line of the header')
    
note

El archivo generado debe superar la orden msgfmt --check de este programa de GNU.


GetText

Gets the translated string corresponding to the given msgid argument.

Se puede definir una lista de argumentos para reemplazar los sustitutivos (%1, %2…) en la cadena.

Si no se encontrare ninguna cadena traducida, el método devolverá la cadena no traducida con los sustitutivos reemplazados por los argumentos especificados.

Sintaxis:

This method can be called either by the full name GetText or by the shortcut _ (a single underscore):

svc.GetText(msgid: str, args: any[0..*]): str

svc._(msgid: str, args: any[0..*]): str

note

In the ScriptForge library, all methods starting with the "_" character are reserved for internal use only. However, the shortcut _ used for GetText is the only exception to this rule, hence it can be safely used in Basic and Python scripts.


Parámetros:

msgid: The untranslated string, which is the text appearing in the program code. It must not be empty. It may contain any number of placeholders (%1 %2 %3 ...) that can be used to dynamically insert text at runtime.

Besides using a single msgid string, this method also accepts the following formats:

args: Values to be inserted into the placeholders. Any variable type is allowed, however only strings, numbers and dates will be considered.

Ejemplo:

En BASIC

Consider the following code is running on a LibreOffice installation with locale set to "es-ES". Additionally, there is a file "es-ES.po" inside the specified folder that translates the string passed to the GetText method:


      myPO = CreateScriptService("L10N", "C:\myPOFiles\")
      myPO.GetText("Welcome %1! Hope you enjoy this program", "John")
      ' "¡Bienvenido John! Espero que disfrutes de este programa"
    
En Python

      myPO = CreateScriptService('L10N', r"C:\myPOFiles")
      myPO.GetText('Welcome %1! Hope you enjoy this program', 'John')
      # "¡Bienvenido John! Espero que disfrutes de este programa"
    
warning

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.


¡Necesitamos su ayuda!