Локализация

From FreeCAD Documentation
Revision as of 17:47, 19 February 2016 by Kompilainenn (talk | contribs)

Локализация это в общем процесс предоставления програмного обеспечения c пользовательским интерфейсом поддерживающем несколько языков . В FreeCAD вы можете установить язык пользовательского интерфейса в Edit→Preferences→Application. FreeCAD использует Qt чтобы поддерживать несколько языков. В Unix/Linux системах, FreeCAD использует текущие настройки локали(языковые настройки) вашей системы, по умолчаннию.

Помощь с переводом FreeCAD

Одно очень важных дел которые вы можете сделать для FreeCAD, если вы не программист, это помочь с переводом программы на ваш язык. Сейчас это легче чем когда-либо, с использованием Crowdin системы совместного on-line перевода.

Как Переводить

  • Отправляйтесь на страницу проекта перевода FreeCAD на Crowdin;
  • Войдите, создав новый профиль, или воспользовавшись сторонними аккаунтами, такими как ваш GMail адрес;
  • Щелкните на языке с которым вы хотите работать;
  • Начните переводить , щелкнув на кнопке Translate рядом с одним из файлов. Например, FreeCAD.ts cсодержит текстовые строки для главного окна FreeCAD.
  • Вы можете голосовать за существующие переводы, или вы можете создавать свой собственный.
Примечание: Если вы активно принимаете участие в переводе FreeCAD и хотите быть в курсе когда будет готов к запуску следующий релиз, так чтобы было время рассмотреть ваш перевод, пожалуйста подпишитесь на этот опрос: http://www.freecadweb.org/tracker/view.php?id=137


Перевод с помощью Qt-Linguist (старый способ)

The following information doesn't need to be used anymore and will likely become obsolete.

It is being kept here so that programmers may familiarize themselves with how it works.

  • Open all of the language folders of FreeCAD shown below
  • Verify that a .ts file with your language code doesn't exist ("fr" for french, "de" for german, etc...)
  • If it exists, you can download that file, if you want to modify/review/better the translation (click the file, then download)
  • If it doesn't exist, download the .ts file without language code (or any other .ts available, it will work too)
  • Rename that file with your language code
  • Open it with the Qt-Linguist program
  • Start translating (Qt Linguist is very easy to use)
  • Once it's completely done, save your file
  • send the files to us so we can include them in the freecad source code so they benefit other users too.

Available translation files

Подготовка собственных модулей/приложений для перевода

Требования

Для локализации вашего модуля приложения вам понадобятся помошники которые поставляются с Qt. Вы можете скачать их с Trolltech-Website, а также они содержаться в LibPack:

qmake
Создает файлы проекта
lupdate
Извлекает или обновляет оригинальные тексты в вашем проекте , сканируя исходный код
Qt-Linguist
Qt-Linguist очень прост в использовании и поможет вам переводить отличными функциями , вроде сборника общих предложений.

Настройка Проекта

Для начала локализации перейдите в GUI-часть вашего модуля и в командной строке введите:

qmake -project

Это просканирует каталог вашего проекта на наличие файлов содержащих текстовые строки и создаст фал проекта , как в следующем примере:

 ######################################################################
 # Automatically generated by qmake (1.06c) Do 2. Nov 14:44:21 2006
 ######################################################################
 
 TEMPLATE = app
 DEPENDPATH += .\Icons
 INCLUDEPATH += .
 
 # Input
 HEADERS += ViewProvider.h Workbench.h
 SOURCES += AppMyModGui.cpp \
            Command.cpp \
            ViewProvider.cpp \
            Workbench.cpp
 TRANSLATIONS += MyMod_de.ts

Вы можете вручную добавить сюда файлы. Раздел TRANSLATIONS содержит список файлов с переводом для каждого языка. В приведенном выше примере MyMod_de.ts является переводом на немецкий.

Теперь вам нужно запустить lupdate чтобы извлечь все строки символьные строки из вашего GUI. Запускайте lupdate после внесения изменений в исходном коде это безопасно, так как она(программа) никогда не удаляет строки из ваших файлов переводов. Она только добоваляет новые строки.

Теперь, необходимо добавить .ts- файлы в ваш проект в VisualStudio. Укажите для них следующий пользовательский метод построения:

python ..\..\..\Tools\qembed.py "$(InputDir)\$(InputName).ts"
                 "$(InputDir)\$(InputName).h" "$(InputName)"

Примечание: Введите это в командной строе, разрывая строку команды только для написания расположения цели.

Компилируя .ts-файл из примера выше, будет создан файл MyMod_de.h. Лучше всего его включить в App<Modul>Gui.cpp. В нашем примереэто должен быть AppMyModGui.cpp. Туда вы добавите строчку

new Gui::LanguageProducer("Deutsch", <Modul>_de_h_data, <Modul>_de_h_len);

для публикации перевода в приложении.

Настройка python файлов для перевода

Для облегчения локализации py файлов вы можете использовать инструмент "pylupdate4" , он принимает один или несколько py фалов. С -ts опцией вы можете подготовить/обновить один или более .ts файлов. Например, чтобы подготовить .ts файл для французского просто введите в командной строке:

pylupdate4 *.py -ts YourModule_fr.ts 

Инструмент pylupdate просканирует ваши .py фалы на наличие translate() или tr() функций и создаст YourModule_fr.ts файл. Этот файл может быть переведен с помощью QLinguist и YourModule_fr.qm файла созданого в QLinguist или с помощью команды

lrelease YourModule_fr.ts

Помните что pylupdate4 не очень хорошо распознает функцию translate(), её необходимо корректно отредактировать ( смотри файлы Draft module как примеры). Внутри вашего файла, вы можете настроить переводчик , как здесь (после загрузки вашей QApplication но ПЕРЕД созданием qt виджетов):

translator = QtCore.QTranslator()
translator.load("YourModule_"+languages[ln])
QtGui.QApplication.installTranslator(translator)

По желанию, вы можете создать XML файл Draft.qrc со следующим содержанием:

  
<RCC>
<qresource prefix="/translations" > 
<file>Draft_fr.qm</file> 
</qresource> 
</RCC> 

и запустив pyrcc4 Draft.qrc -o qrc_Draft.py создайти приложение(big Python) содержащее все ваши ресурсы. Кстати этот подход также работает для помещения значка в один из фалов ресурсов

Перевод wiki

В этой вики содержится много контента, большинство из которого собрано в руководства. Вы можете просмотреть документацию, начиная со стартовой страницы или можно взглянуть на руководство пользователя

Translation plugin

When the Wiki moved away from SourceForge, Yorik installed a Translation plugin which allows to ease translations between pages. For example, the page title can now be translated. Other advantages of the Translation plugin are that it keeps track of translations, notifies if the original page has been updated, and maintains translations in sync with the original English page.

The tool is documented in Extension:Translate, and is part of a Language Extension Bundle.

To quickly get started on preparing a page for translation and activating the plugin, please read the Page translation example.

To see an example of how the Translation tool works once the translation plugin is activated on a page, you can visit the Main Page. You will see a new language menu bar at the bottom. It is automatically generated. Click for instance on the German link, it will get you to Main Page/de. Right under the title, you can read "This page is a translated version of a page Main Page and the translation is xx% complete." (xx being the actual percentage of translation). Click on the "translated version" link to start translation, or to update or correct the existing translation.

You will notice that you cannot directly edit a page anymore once it's been marked as a translation. You have to go through the translation utility.

When adding new content, the English page should be created first, then translated into another language. If someone wants to change/add content in a page, he should do the English one first.

It is recommended to have basic knowledge of wiki style formatting and general guidelines of the FreeCAD wiki, because you will have to deal with some tags while translating. You can find this information on WikiPages.

The sidebar (navigation menu on the left) is also translatable. Please follow dedicated instructions on Localisation Sidebar page.

REMARK: The first time you switch a page to the new translation system, it looses all its old 'manual' translations. To recover the translation, you need to open an earlier version from the history, and copy/paste manually the paragraphs to the new translation system.

Remark: to be able to translate in the wiki, you must of course gain wiki edit permission.


If you are unsure how to proceed, don't hesitate to ask for help in the forum.

Old translation instructions

These instructions are for historical background only, while the pages are being passed to the new translation plugin.

So the first step is to check if the manual translation has already been started for your language (look in the left sidebar, under "manual").
If not, head to the forum and say that you want to start a new translation, we'll create the basic setup for the language you want to work on.
You must then gain wiki edit permission.
If your language is already listed, see what pages are still missing a translation (they will be listed in red). The technique is simple: go into a red page, and copy/paste the contents of the corresponding English page, and start translating.
Do not forget to include all the tags and templates from the original English page. Some of those templates will have an equivalent in your language (for example, there is a French Docnav template called Docnav/fr). You should use a slash and your language code in almost all the links. Look at other already translated pages to see how they did it.
Add a slash and your language code in the categories, like [[Category:Developer Documentation/fr]]
And if you are unsure, head to the forums and ask people to check what you did and tell you if it's right or not.
Four templates are commonly used in manual pages. These 4 templates have localized versions (Template:Docnav/fr, Template:fr, etc...)

  • Template:GuiCommand : is the Gui Command information block in upper-right of command documentation.
  • Template:Docnav : it is the navigation bar at the bottom of the pages, showing previous and next pages.

Page Naming Convention
Please take note that, due to limitations in the Sourceforge implementation of the MediaWiki engine, we require that your pages all keep their original English counterpart's name, appending a slash and your language code. For example, the translated page for About FreeCAD should be About Freecad/es for Spanish, About FreeCAD/pl for polish, etc. The reason is simple: so that if translators go away, the wiki's administrators, who do not speak all languages, will know what these pages are for. This will facilitate maintenance and avoid lost pages.
If you want the Docnav template to show linked pages in your language, you can use redirect pages. They are basically shortcut links to the actual page. Here is an example with the French page for About FreeCAD.

  • The page About FreeCAD/fr is the page with content
  • The page À propos de FreeCAD contains this code:
#REDIRECT [[About FreeCAD/fr]]
  • In the About FreeCAD/fr page, the Docnav code will look like this:
{{docnav/fr|Bienvenue sur l'aide en ligne|Fonctionnalités}}

The page "Bienvenue sur l'aide en ligne" redirects to Online Help Startpage/fr, and the page "Fonctionnalités" redirects to Feature list/fr.

Branding/ru
Extra python modules/ru