ScriptForge. Serviço L10N

Este serviço disponibiliza vários métodos relacionados com a tradução de cadeias de caracteres, com um impacto mínimo no código-fonte do programa. Os métodos disponibilizados pelo serviço L10N podem ser utilizados principalmente para:

Ícone de nota

A sigla L10N significa «Localização» e refere-se a um conjunto de procedimentos destinados à tradução de software para um país ou região específicos.


Os ficheiros PO têm vindo a ser promovidos há muito tempo na comunidade do software livre como um meio de proporcionar interfaces de utilizador multilingues. Isto é conseguido através da utilização de ficheiros de texto legíveis por humanos, com uma estrutura bem definida que especifica, para qualquer idioma, a cadeia de caracteres do idioma de origem e a cadeia de caracteres localizada.

A principal vantagem do formato PO é a separação entre o programador e o tradutor. Os ficheiros PO são ficheiros de texto independentes, pelo que o programador pode enviar ficheiros de modelo POT aos tradutores, que, por sua vez, traduzirão o seu conteúdo e devolverão os ficheiros PO traduzidos para cada idioma suportado.

Ícone da dica

O serviço L10N baseia-se na implementação GNU dos ficheiros PO (objeto portátil). Para saber mais sobre este formato de ficheiro, visite Utilitários GNU gettext: Ficheiros PO.


Este serviço implementa os métodos abaixo indicados:

Ícone de nota

Note-se que os dois primeiros métodos são utilizados para criar um conjunto de cadeias de texto traduzíveis e exportá-las para um ficheiro POT. No entanto, não é obrigatório criar ficheiros POT utilizando estes métodos. Uma vez que se trata de ficheiros de texto, o programador poderia tê-los criado utilizando qualquer editor de texto.


Chamada de serviço

Antes de utilizar o serviço L10N, é necessário carregar ou importar a biblioteca ScriptForge:

Ícone de nota

• As macros básicas requerem o carregamento da biblioteca ScriptForge através da seguinte instrução:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Os scripts Python requerem a importação do módulo scriptforge:
from scriptforge import CreateScriptService


Existem várias formas de invocar o serviço L10N utilizando até cinco argumentos opcionais que especificam a pasta onde os ficheiros PO estão armazenados, a localização e a codificação a utilizar, bem como um ficheiro PO de reserva e a respetiva codificação.

Sintaxe:

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

nome da pasta: A pasta que contém os ficheiros PO. Deve ser expressa na notação FileSystem.FileNaming.

locale: Uma cadeia de caracteres no formato «la-CO» (língua-PAÍS) ou apenas no formato «la» (língua).

codificação: O conjunto de caracteres a utilizar. A codificação predefinida é «UTF-8».

locale2: Uma cadeia de caracteres que especifica a localização alternativa a utilizar caso o ficheiro PO correspondente à localização definida no parâmetro locale não exista. Este parâmetro é expresso apenas na forma «la-CO» (língua-PAÍS) ou «la» (língua).

encoding2: O conjunto de caracteres do ficheiro PO de recurso correspondente ao argumento locale2. A codificação predefinida é «UTF-8».

Ícone de nota

Para saber mais sobre os nomes dos conjuntos de caracteres, visite a página Conjuntos de Caracteres da IANA. Tenha em atenção que o LibreOffice não implementa todos os conjuntos de caracteres existentes.


Exemplo:

Em Basic

O exemplo seguinte instancia o serviço L10N sem quaisquer argumentos opcionais. Isto ativará apenas os métodos AddText e ExportToPOTFile, o que é útil para criar ficheiros POT.


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

O exemplo abaixo especifica a pasta que contém os ficheiros PO. Como a localização não está definida, a instância do serviço utilizará a localização definida para a interface de utilizador do LibreOffice, que é a mesma localização definida na propriedade OfficeLocale do serviço Platform.


      Set myPO = CreateScriptService("L10N", "C:\myPOFiles")
    
Ícone de aviso

O exemplo acima resultará num erro de execução se o ficheiro PO correspondente à localização OfficeLocale não existir na pasta especificada.


No exemplo abaixo, a localização é explicitamente definida como francês belga («fr-BE»), pelo que o serviço irá carregar o ficheiro «fr-BE.po» a partir da pasta «C:\myPOFiles». Se o ficheiro não existir, ocorrerá um erro.


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

Para evitar erros, é possível especificar uma localização e uma codificação preferenciais e alternativas. O exemplo seguinte tentará, em primeiro lugar, carregar o ficheiro «fr-BE.po» a partir da pasta especificada e, caso este não exista, será carregado o ficheiro «en-US.po».


      Set myPO = CreateScriptService("L10N", "C:\myPOFiles", "fr-BE", "UTF-8", "en-US", "UTF-8")
    
Ícone da dica

Os ficheiros PO devem ser nomeados no formato «la-CO.po» ou «la.po», em que «la» se refere ao idioma e «CO» ao país. Alguns exemplos são: «en-US.po», «fr-BE.po» ou «fr.po».


Recomenda-se libertar os recursos após a utilização:


      Set myPO = myPO.Dispose()
    
Em Python

Os exemplos acima podem ser traduzidos para Python da seguinte forma:


      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()
    
Ícone de nota

Podem coexistir várias instâncias do serviço L10N. No entanto, cada instância deve utilizar um diretório distinto para os seus ficheiros PO.


Características

Nome

Readonly

Type

Description

Folder

Yes

String

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

Languages

Yes

Array

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

Locale

Yes

String

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


List of Methods in the L10N Service

AddText
AddTextsFromDialog

ExportToPOTFile

GetText


AddText

Adds a new entry in the list of localizable strings. It must not exist yet.

The method returns True if successful.

Sintaxe:

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.

Exemplo:

The example below creates a set of strings in English:

Em 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")
    
Em 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.

Ícone de nota

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.

Sintaxe:

svc.AddTextsFromDialog(dialog: svc): bool

Parâmetros:

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

Exemplo:

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

Em Basic

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

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

ExportToPOTFile

Exports a set of untranslated strings as a POT file.

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.

Sintaxe:

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

Parâmetros:

filename: The full output file name 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").

Exemplo:


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

      # Python
      myPO.ExportToPOTFile('C:\myFile.pot', header = 'First line of the header\nSecond line of the header')
    
Ícone de nota

The generated file should successfully pass the msgfmt --check GNU command.


GetText

Gets the translated string corresponding to the given msgid argument.

A list of arguments may be specified to replace the placeholders (%1, %2, ...) in the string.

If no translated string is found, the method returns the untranslated string after replacing the placeholders with the specified arguments.

Sintaxe:

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

Ícone de nota

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.

Exemplo:

Em 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"
    
Em 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"
    
Ícone de aviso

Todas as rotinas ou identificadores do ScriptForge Basic que tenham o caractere de sublinhado «_» como prefixo estão reservados para uso interno. Não se destinam a ser utilizados em macros do Basic ou em scripts Python.


Necessitamos da sua ajuda!

Necessitamos da sua ajuda!