Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Локализация с помощью gettext

In addition to Импорт переводов in CSV format, Godot also supports loading translation files written in the GNU gettext format (text-based .po and compiled .mo since Godot 4.0).

Примечание

Для ознакомления с gettext посмотрите A Quick Gettext Tutorial. Он написан для проектов на C, но большая часть советов применима и к Godot (за исключением xgettext).

Преимущества

  • gettext - это стандартный формат, который можно редактировать с помощью любого текстового редактора или редакторов с графическим интерфейсом, таких как Poedit.

  • gettext поддерживается такими платформами перевода, как Transifex и Weblate, что облегчает совместную работу людей над локализацией.

  • По сравнению с CSV, gettext лучше работает с системами контроля версий, такими как Git, поскольку каждая локаль имеет свой собственный файл сообщений.

  • Многострочные строки удобнее редактировать в gettext-файлах по сравнению с CSV-файлами.

Недостатки

  • gettext - это более сложный формат, чем CSV, и его может быть труднее понять тем, кто только начинает заниматься локализацией программного обеспечения.

  • People who maintain localization files will have to install gettext tools on their system. However, as Godot supports using text-based message files (.po), translators can test their work without having to install gettext tools.

Установка инструментов gettext

Инструменты командной строки gettext необходимы для выполнения операций обслуживания, таких как обновление файлов сообщений. Поэтому настоятельно рекомендуется их установить.

  • Windows: Загрузите программу установки с этой страницы <https://mlocati.github.io/articles/gettext-iconv-windows.html>`_. Работает любая архитектура и бинарный тип (разделяемый или статический); если есть сомнения, выбирайте 64-битный статический инсталлятор.

  • macOS: Установите gettext либо с помощью Homebrew с командой brew install gettext, либо с помощью MacPorts <https://www.macports.org/>`_ с командой ``sudo port install gettext.

  • Linux: В большинстве дистрибутивов установите пакет ``gettext'' из менеджера пакетов вашего дистрибутива.

Creating the PO template

Automatic generation using the editor

Since Godot 4.0, the editor can generate a PO template automatically from specified scene and GDScript files. This POT generation also supports translation contexts and pluralization if used in a script, with the optional second argument of tr() and the tr_n() method.

Open the Project Settings' Localization > POT Generation tab, then use the Add… button to specify the path to your project's scenes and scripts that contain localizable strings:

Creating a PO template in the Localization > POT Generation tab of the Project Settings

Creating a PO template in the Localization > POT Generation tab of the Project Settings

After adding at least one scene or script, click Generate POT in the top-right corner, then specify the path to the output file. This file can be placed anywhere in the project directory, but it's recommended to keep it in a subdirectory such as locale, as each locale will be defined in its own file.

You can then move over to creating a messages file from a PO template.

Примечание

Remember to regenerate the PO template after making any changes to localizable strings, or after adding new scenes or scripts. Otherwise, newly added strings will not be localizable and translators won't be able to update translations for outdated strings.

Manual creation

If the automatic generation approach doesn't work out for your needs, you can create a PO template by hand in a text editor. This file can be placed anywhere in the project directory, but it's recommended to keep it in a subdirectory, as each locale will be defined in its own file.

Create a directory named locale in the project directory. In this directory, save a file named messages.pot with the following contents:

# Don't remove the two lines below, they're required for gettext to work correctly.
msgid ""
msgstr ""

# Example of a regular string.
msgid "Hello world!"
msgstr ""

# Example of a string with pluralization.
msgid "There is %d apple."
msgid_plural "There are %d apples."
msgstr[0] ""
msgstr[1] ""

# Example of a string with a translation context.
msgctxt "Actions"
msgid "Close"
msgstr ""

Сообщения в gettext состоят из пар msgid и msgstr. msgid - это исходная строка (обычно на английском языке), msgstr - это переведенная строка.

Предупреждение

Значение msgstr в файлах шаблонов PO (.pot) должно всегда быть пустым. Локализация будет выполнена в сгенерированных файлах .po вместо этого.

Создание файла сообщений из шаблона PO

Команда msginit используется для превращения шаблона PO в файл сообщений. Например, чтобы создать файл французской локализации, используйте следующую команду, находясь в каталоге locale:

msginit --no-translator --input=messages.pot --locale=fr

Приведенная выше команда создаст файл с именем fr.po в том же каталоге, что и шаблон PO.

Кроме того, это можно сделать графически с помощью Poedit или загрузив файл POT на выбранную вами веб-платформу.

Загрузка файла сообщений в Godot

To register a messages file as a translation in a project, open the Project Settings, then go to the Localization tab. In Translations, click Add… then choose the .po or .mo file in the file dialog. The locale will be inferred from the "Language: <code>\n" property in the messages file.

Примечание

Смотрите Локализация игр для получения дополнительной информации об импорте и тестировании переводов в Godot.

Обновление файлов сообщений в соответствии с шаблоном PO

После обновления шаблона PO вам нужно будет обновить файлы сообщений, чтобы они содержали новые строки, удалив при этом строки, которые больше не присутствуют в шаблоне PO. Это можно сделать автоматически с помощью инструмента msgmerge:

# The order matters: specify the message file *then* the PO template!
msgmerge --update --backup=none fr.po messages.pot

Если вы хотите сохранить резервную копию исходного файла сообщения (который в данном примере будет сохранен как fr.po~), удалите аргумент --backup=none.

Примечание

After running msgmerge, strings which were modified in the source language will have a "fuzzy" comment added before them in the .po file. This comment denotes that the translation should be updated to match the new source string, as the translation will most likely be inaccurate until it's updated.

Strings with "fuzzy" comments will not be read by Godot until the translation is updated and the "fuzzy" comment is removed.

Проверка достоверности файла или шаблона PO

Проверить правильность синтаксиса файла gettext можно, выполнив приведенную ниже команду:

msgfmt fr.po --check

Если есть синтаксические ошибки или предупреждения, они будут выведены в консоль. В противном случае ``msgfmt'' ничего не выведет.

Using binary MO files (useful for large projects only)

For large projects with several thousands of strings to translate or more, it can be worth it to use binary (compiled) MO message files instead of text-based PO files. Binary MO files are smaller and faster to read than the equivalent PO files.

You can generate a MO file with the command below:

msgfmt fr.po --no-hash -o fr.mo

If the PO file is valid, this command will create a fr.mo file besides the PO file. This MO file can then be loaded in Godot as described above.

The original PO file should be kept in version control so you can update your translation in the future. In case you lose the original PO file and wish to decompile a MO file into a text-based PO file, you can do so with:

msgunfmt fr.mo > fr.po

The decompiled file will not include comments or fuzzy strings, as these are never compiled in the MO file in the first place.