Example project for translation lazarus / 31-LCL ---------------------------------------------------------------------- wp · 2013-12-06 17:13 Here is another example showing how to translate an application to various languages. The example is somehow based on my tutorial on this subject (http://wiki.lazarus.freepascal.org/Step-by- step_instructions_for_creating_multi-language_applications). In addition, it shows how to - handle translation of combobox strings - create translated strings by using the format statement - change translation at runtime - switch format settings - use a shared resource string unit - update language in several open forms. A brief description of steps is contained in the main unit. I guess some important items are still missing. In particular, I do not treat BiDi here since I am left-to-right only. But I would appreciate if somebody from these regions could have a look and add modifications. It would be fine if we could propose this project as an official Lazarus example. Note: Lazarus 1.2RC or trunk needed for run-time switching of languages. ---------------------------------------------------------------------- kpeters58 · 2013-12-06 18:04 Nice work - thanks! ---------------------------------------------------------------------- wp · 2013-12-07 20:34 Here is an update showing more details of format settings. This version covers BiDiMode as well. Select language "Hebrew" to see right-to-left mode. I know from another posting in this forum that the pagecontrol of Lazarus is not correct in this mode, but the rest of the demo application should work properly. @Avishai: Would you mind to translate the Hebrew language file? Load it into poedit (http://sourceforge.net/projects/poedit/) and add the translated strings - it is easy! And it would be great if you could give me hints on missing critical items. ---------------------------------------------------------------------- Windsurfer · 2013-12-08 18:01 Hi wp, It is a great example. I have tested it and it looks great, including the explanations. When I compiled it, the following messages were shown: Options changed, recompiling clean with -B Compiling translation_demo.lpr Compiling main.pas Compiling localizedforms.pas localizedforms.pas(56,67) Warning: Local variable "nchars" does not seem to be initialized localizedforms.pas(90,10) Warning: Function result does not seem to be set localizedforms.pas(93,3) Note: Local variable "lng" not used localizedforms.pas(90,30) Hint: Parameter "ALang" not used localizedforms.pas(163,3) Warning: Symbol "GetLocaleFormatSettings" is not portable localizedforms.pas(172,3) Note: Local variable "i" not used I have not looked very closely, but i does not need to be declared twice in FlipChildren and lng should be commented out in the var section. ALang possibly needs a comment to explain the compiler hint. ---------------------------------------------------------------------- wp · 2013-12-08 19:00 No warnings in the attached version... ---------------------------------------------------------------------- eny · 2013-12-08 20:49 Great contribution wp! I might even start using localization myself ---------------------------------------------------------------------- Avishai · 2013-12-08 21:35 I was trying to stay out of this topic, but since you were kind enough to ask me directly I'll give you the best answer I can. For MSWindows platform, there is no point in trying to add RightToLeft to your globalization.  Lazarus doesn't support RightToLeft on MSWindows. For other platforms, you would have to ask someone that uses them and knows what is required for RightToLeft because I don't know what kind of support they have for RightToLeft. ---------------------------------------------------------------------- wp · 2013-12-08 22:01 Quote Lazarus doesn't support RightToLeft on MSWindows.This answer confuses me a lot: There is BiDiMode, there is FlipChildren, most controls are reacting in a way that appears reasonable to me and which is the same as in Delphi, except for a few buggy ones - I patched three of them (TRadioGroup, TCheckGroup, TCheckListbox) yesterday in http://mantis.freepascal.org/view.php?id=25408. So, what is missing to justify that harsh statement? In the example posted above, select language Hebrew to see RightToLeft with Lazarus on Windows - at least in my understanding of what RTL should look like from what I learned from your postings here. ---------------------------------------------------------------------- Avishai · 2013-12-08 22:50 Thant's why I was trying to stay out of this topic.  But I'll try to give you at least a partial answer. Everything I say here is MSWindows related.  I don't know other OSs. To the best of my knowledge you can not set TForm to be RightToLeft.  You can set BiDiMode:= bdRightToLeft, but it does not create a RightToLeft Form.  A RightToLeft Form has the Close button on the Left and the Caption/Icon on the Right.  LeftToRight Forms are not acceptable. None of the controls on the Common Controls Tab or that descend from them and have a direction are drawn RightToLeft when BiDiMode:= bdRightToLeft and most don't publish BiDiMode. Many of the Dialog Boxes are LeftToRight only and have to be manipulated in ways that can not be considered to be acceptable.  Even a simple MessageBox. Far too many Lazarus Controls either lack BiDi support or can't draw themselves RightToLeft. Other that TBarChart, I haven't even looked at the Charts.  But my guess is that they can not draw RightToLeft. The bottom line is that if I have to write a serious RightToLeft application, I have to turn to some other tool than Lazarus.  And believe me, I hate saying that. I think what bothers me most is that Lazarus is so very close to being a great RightToLeft tool.  Almost everything is already there and working.  It just takes that one final step. ---------------------------------------------------------------------- wp · 2013-12-08 23:07 Thanks for this answer anyway. From what I saw yesterday when comparing Delphi and Lazarus for the bugreport mentioned above, I realised that some of these issues apply also to Delphi: In RTL mode, the form's Close button is at the right as well, the pagecontrol and treeview don't change when switching BiDiMode. When trying to fix BiDiMode for TPageControl I read that BiDiMode is not implemented by Microsoft for the common controls - then we are out of luck with Lazarus as well, at least for the native controls. I'll have to take a look at VirtualTreeView which is written without Microsoft controls. [EDIT]: VirtualTreeView does support BiDiMode and look reasonable, it is still some kind of buggy, though. ---------------------------------------------------------------------- Avishai · 2013-12-08 23:23 In Delphi it is a very simple thing to produce a RightToLeft application. Code: [Select]Type   TForm1 = Class(TForm)     ...     procedure CreateParams(var Params: TCreateParams); override;   End; Implementation procedure TForm1.CreateParams(var Params: TCreateParams); begin   inherited CreateParams(Params);   if SysLocale.MiddleEast then     Params.ExStyle:= Params.ExStyle or WS_EX_LAYOUTRTL; end; Initialization   SysLocale.MiddleEast:= True; This Mirrors everything.  You don't even set BiDiMode:= bdRightToLeft or change the Anchors.  Mirroring takes care of almost everything with only a few trivial 'fixups' to do. But you can't do this in Lazarus.  There is a bug with TCanvas that I reported over 2 years age.  When you use MS Mirroring Technology it corrupts TCanvas and it can't be used. I've looked for 2 years to find the problem and I'm no closer today than the day I started.  My skills aren't good enough. See Bug Report #20506 Edit:  Mirroring also takes care of the Anchors.  It doesn't change the anchors.  If controls are anchored to the Left, they still are.  But the "Left" is now on the Right side of the Form and the "Right" is now on the  Left side of the Form. ---------------------------------------------------------------------- Avishai · 2013-12-08 23:41 This is just something my friend put together quickly in Delphi to show how easy it is to make a true R2L Form. ---------------------------------------------------------------------- wp · 2013-12-08 23:46 QuoteThis Mirrors everything.Yes I see: Just started Delphi XE2, new project, add a pagecontrol to a form, used your code (without the SysLocale.MiddleEast) - and the form is mirrored! So that entire thing with BiDiMode is just outdated? ---------------------------------------------------------------------- Avishai · 2013-12-08 23:52 BiDiMode isn't entirely outdated.  There are a few cases where it may still be useful (although I don't know where).  FlipChildren is definatel obsolete.  At least for MSWindows. The few fixups for Delphi are things like reversing the Right/Left arrow keys when in a StringGrid and some other trivial thing like that.  But for the most part, that tiny bit of code takes care of *almost* everything. ---------------------------------------------------------------------- Avishai · 2013-12-09 00:07 I just remembered where you still need BiDiMode.  If you have a RightToLeft Form, but need a LeftToRight Control on that Form, you set the BiDiMode:= bdRightToLeft.  Backward from what you want. Two Rights make a Left. ---------------------------------------------------------------------- Avishai · 2013-12-09 00:32 Here is some more R2L code you might find interesting. Code: [Select]function IsMirrored(ACtrl: TObject): Boolean; begin   Result:= False;   if ACtrl is TWinControl then     Result:= (GetWindowLong(TWinControl(ACtrl).Handle, GWL_EXSTYLE)       and WS_EX_LAYOUTRTL)<>0; end; procedure RTLCtrl(ACtrl: TObject); { Make TWinControl RightToLeft - MSWindows ONLY! } begin   if ACtrl is TWinControl then     with TWinControl(ACtrl) do       SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYOUTRTL); end; procedure LTRCtrl(ACtrl: TObject); { Make TWinControl LeftToRight - MSWindows ONLY! } begin   if ACtrl is TWinControl then     with TWinControl(ACtrl) do       SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) and WS_EX_LAYOUTRTL); end; ---------------------------------------------------------------------- CM630 · 2013-12-19 07:39 Thanks for the good explanation. There are two major point that is not mentioned. 1. All interface items must be autosized, since strings have different length in each language. In my opinion, if the main interface is in English, at least 50% more space shall be considered. 2. Anchoring must be used, to prevent overlaps. I added a GUI Design section in the wiki. 3. ShowMessage is not proper for localization, because the OK, Cancel, Yes, No, etc. strings will be retrieved from the language of the OS (or LCL?? which might not be translated). QuestionDlg is a much better solution. The thing I hate about is that I cannot find out how to remove the delphi-like icons from the buttons. Because QuestionDialog takes too much parameters, things mighty be made easier: Code: [Select]procedure MsgBox (aString: string); begin     QuestionDlg (SMessage,aString,mtCustom,[mrOK,SOK],''); end; ---------------------------------------------------------------------- wp · 2013-12-19 08:17 Thank you. I added another sentence on positioning of label above the controls instead of to the left. ---------------------------------------------------------------------- Avishai · 2013-12-19 08:25 This is a good point.  I normally anchor the Label to both the Left and Right side of the Control and set Label.WordWrap:= true so that it can become multi-line when needed.  But you have to plan the layout to allow for that vertical growth.  I guess everyone has their own methods. ---------------------------------------------------------------------- rasberryrabbit · 2013-12-19 08:35 Quote from: paskal on December 19, 2013, 08:39:07 am3. ShowMessage is not proper for localization, because the OK, Cancel, Yes, No, etc. strings will be retrieved from the language of the OS. QuestionDlg is a much better solution. The thing I hate about is that I cannot find out how to remove the delphi-like icons from the buttons. Dialog localization can translated with LCLStrConsts.(lang).po Files. like this Code: [Select]  Translations.TranslateUnitResourceStrings('LCLStrConsts', 'lclstrconsts.%s.po', lng, lngf); ---------------------------------------------------------------------- CM630 · 2013-12-19 08:56 Yes, but can separate LCL translations for your application? One of the cases is when LCL is not translated. Then you expect the translator of your app to translate it and to send it to someone from the Lazarus project. Well, the translator might have no idea what Lazarus is. Also, that might mean that he/she will be have to translate out of the context, which is not a nice idea. The second case is when LCL is translated. Then practically you have one translator translating LCL, and another one, translating you application. This could cause inconsistency. I would do anything possible not to use a string, which is translatable out of my application. Edit: I just came to  http://wiki.lazarus.freepascal.org/Step-by- step_instructions_for_creating_multi- language_applications#Strings_defined_by_the_LCL. I will take some time to comprehend it. Edit: If I understand the sentence  This works because resourcestrings are pulled in from all language files for the active language found in the languages folder right, one might have the same strings from LCL in his project and the strings from his project will have a higher priority? ---------------------------------------------------------------------- wp · 2013-12-19 09:40 To make it clear: to have LCL strings translated you copy lclstrconsts.*.po to your languages folder, and then you can modify them in any way you want - LCL translations are completely coupled off of Lazarus. @parcel: There is no need to call TranslateUnitResourceStrings, this is done by Defaulttranslator automatically. Unfortunately, there's a lot of common dialogs where strings are defined by the OS and cannot be changed that easily... ---------------------------------------------------------------------- CM630 · 2013-12-19 10:13 There is one more issue. For example I have: Code: [Select]resourcestring   SFileDoesNotExist = 'File does not exist.'; begin   ShowMessage(SFileDoesNotExist); end;But I want to put the name of the file inside. I can use nor  ShowMessage(SFileDoesNotExist + filename); neither  ShowMessage(SFile + filename + SDoesNotExist); because word order might vary. There was some trick with %something. It shall be written in the wiki. Quote from: wp on December 19, 2013, 10:40:47 am Unfortunately, there's a lot of common dialogs where strings are defined by the OS and cannot be changed that easily... So if ShowMessage is one of these, it shall not be used. ---------------------------------------------------------------------- taazz · 2013-12-19 10:42 use format eg Code: [Select]resourcestring   SFileDoesNotExist = 'File <%S> not found'; ... begin ... ShowMessage(format(SFileDoesNotExist ,[ filename]); ---------------------------------------------------------------------- Avishai · 2013-12-19 10:55 You have a lot of flexibility with MessageDlg.  This code shows how to add some things but it's just garbage to show how to do it. Edit: I just added code to get rid of the "delphi-like icons". Code: [Select]procedure TForm1.btnMeassageClick(Sender: TObject); var   RtlMessageDlg: TForm;   I: Integer;   ALabel: TLabel;   Radio: TRadioButton; begin   RtlMessageDlg:= CreateMessageDialog('This is the Message Text.', mtConfirmation,[mbOK, mbCancel]);   RtlMessageDlg.Caption:= 'A Caption';   RtlMessageDlg.Controls[0].Caption:= 'Ok button Text';   TBitBtn(RtlMessageDlg.Controls[0]).Glyph:= Nil;  // Get rid of delphi-like icons   RtlMessageDlg.Controls[1].Caption:= 'Cancel button Text';   for I:= 0 to RtlMessageDlg.ControlCount-1 do     RtlMessageDlg.Controls[I].BiDiMode:= bdRightToLeft;   RtlMessageDlg.Width:= RtlMessageDlg.Width*2;   RtlMessageDlg.Height:= RtlMessageDlg.Height*2;   ALabel:= TLabel.Create(Self);   ALabel.Caption:= 'Some Text to Show!';   ALabel.Parent:= RtlMessageDlg;   ALabel.Align:= alBottom;   ALabel.Alignment:= taCenter;   Radio:= TRadioButton.Create(Self);   Radio.Caption:= 'Some Text to Show!';   Radio.Parent:= RtlMessageDlg;   Radio.Align:= alBottom;   RtlMessageDlg.ShowModal;   FreeAndNil(RtlMessageDlg); end; ---------------------------------------------------------------------- CM630 · 2013-12-19 11:40 So it goes: Code: [Select]resourcestring  SFilesProcessed = '%d out of %d files processed in folder „%s.“' ...  ShowMessage(format(SFilesProcessed ,[27,49,'c:\']));  I suppose the answer is No, but there is probably no inbuilt function to replace the %d and %s with numbers? To translate this line I have to do Обработени са % change_keyboard_layoutdchange_keyboard_layout файла от общо   %change_keyboard_layoutdchange_keyboard_layout в папка %change_keyboard_layoutschange_keyboard_layout If these chars were number I would simply do: Обработени са %1 файла от общо %2 в папка „%3“. ---------------------------------------------------------------------- taazz · 2013-12-19 12:03 erm have you test it and it didn't work? Because what you have posted is the correct way to replace %D with numbers, integer numbers, of course there are more defines you can use for various data types as well, take a closer look on the Format description. ---------------------------------------------------------------------- wp · 2013-12-19 12:12 Quoteresourcestring  SFilesProcessed = '%d out of %d files processed in folder „%s.“'And I'd use indices in the format specifier because the order of parameters may change from language to language. This is better: Code: [Select]resourcestring  SFilesProcessed = '%0:d out of %1:d files processed in folder „%2:s.“' begin ...   ShowMessage(Format(SFilesProcessed, [27, 49, 'c:\'])); Therefore, the given format statement would still be valid if the translated version would be (back-translated to english) 'In folder "%2:s", %0:d out of %1 files were processed.' ---------------------------------------------------------------------- CM630 · 2013-12-19 12:49 Quote from: taazz on December 19, 2013, 01:03:28 pmerm have you test it and it didn't work?No, it works. The problem is that it uses Latin characters (s, d, etc) which requires the tranlators to change the keyboard layouts too often. I just wrote a function to show the idea: Code: [Select]Uses ...strutils... ... function LocalizeRowMultiple(const aString:string; const Args: array of String):string; var    RetVal:string;    i: integer; begin    RetVal:=aString;    for i:= 0 to Length(Args)-1 do    begin       RetVal:= StringsReplace  (RetVal,'%'+IntToStr(i+1), Args[i],[]);    end;    Result:=RetVal ; end; Usage is  SFilesProcessed = '%1 out of %2 files processed in folder „%3.“' @WP, IMHO adding your example in the wiki will be useful. ---------------------------------------------------------------------- taazz · 2013-12-19 13:43 Quote from: paskal on December 19, 2013, 01:49:29 pmNo, it works. The problem is that it uses Latin characters (s, d, etc) which requires the tranlators to change the keyboard layouts too often. 1) you do not know the translators work flow 2) you can leave all the defines to be inserted after the translation, that will make things easier. 3) the format function is open sourced you can take it and change it as needed, eg use only index defines instead of data and use the TVarRec to guess what the user wants to show. ---------------------------------------------------------------------- CM630 · 2013-12-20 12:50 In some languages the sentences might vary, depending on the number of an item. A simple example: 1 file found and 5 files found found. If I am not wrong in Russian, for numbers ending on 1;2;3 and 4 there is one suffix for file , and for the other numbers the suffix is different. The main advantage of PO is exactly handling this item.  So here is what happens: I added ezFilesFound = '%d files found'; I expected that in the PO file there should be added the necessary info, so I would have several strings corresponding to ezFilesFound. Instead I have one string only. What shall I do to have the plural forms okay? Is this supported by Lazarus? Also, there is another issue. Running an app with the --lang bg or --lang ru has no effect for me- applications keep running in English. The PO files are generated (almost) properly, PO Edit validates the files okay. What could Then I tried another Lazarus app- Double Commander the following way: doublecmd.exe --lang de . Still no effect.  The interface did not run in German. What could I have done wrong? ---------------------------------------------------------------------- wp · 2013-12-20 16:43 (1) Plural: As far as I know poedit can handle plural forms, even several plurals as you mention for Russian. I never tried it myself, though. I also don't know how to invoke that feature in the Lazarus code. Google for "poedit plural". If you find out please let us know. (2) Failure to respect "--lang xx": DefaultTranslator provides the infrastructure, but the program, of course, has to consider that. The demo program in this thread, for example, overrides  (i.e. ignores)  that commandline selection by explicitly calling SetDefaultLang('en') in the OnCreate event of the main form. If that feature is activated in your form use the debugger and step through DefaultTranslator.pas - I've seen a few feature that were not working as I had expected. ---------------------------------------------------------------------- hovadur · 2013-12-21 12:04 Quote from: wp on December 19, 2013, 10:40:47 amTo make it clear: to have LCL strings translated you copy lclstrconsts.*.po to your languages folder, and then you can modify them in any way you want - LCL translations are completely coupled off of Lazarus. Can you write it in top comment of main form? ---------------------------------------------------------------------- CM630 · 2014-01-06 13:16 Quote from: Avishai on December 19, 2013, 11:55:33 amYou have a lot of flexibility with MessageDlg.  This code shows how to add some things but it's just garbage to show how to do it. ...Maybe I should mention a problem with your code, causeing buttons to overlap. I fixed it the following way: Code: [Select]  for i:= 0 to RtlMessageDlg.ControlCount-1 do      begin        RtlMessageDlg.Controls[i].AutoSize:= True;        RtlMessageDlg.Controls[i].BiDiMode:= bdRightToLeft;        TBitBtn(RtlMessageDlg.Controls[i]).Glyph:= Nil;  // Get rid of delphi-like icons      end;   RtlMessageDlg.Show;   for i:=1 to RtlMessageDlg.ControlCount-1 do      RtlMessageDlg.Controls[i].Left:=RtlMessageDlg.Controls[i- 1].Left+RtlMessageDlg.Controls[i-1].Width+2 ;   RtlMessageDlg.Hide;    RtlMessageDlg.Show; must be used, because otherwise Lazarus cannot calculate the real widths of the controls. If someone knows a better way, please let me know. ---------------------------------------------------------------------- CM630 · 2014-01-08 07:49 There is another issue. I have several buttons placed vertically, and I want them to have the same width in a language. I mean, I do not mind if they become wider, but all buttons in a a column (same vertical position) shall have an equal width. If I set all the buttons to autosize, they will have different widths (like in columns 1, counting from 0). If I do not, there might not be enough space for the text (like in column 0, row 1). Also, if I have the buttons autosized, then I will have to anchor each button to a button from the same row (normally I would anchor horizontally to the  topmost button of the preceding row). The only solution I can think of is to use autoresize, after all buttons get autoresized to find the width of the widest control in the column, to disable autoresize and to set the width properties of all the buttons in the column. Then I will have to set the .Left property of all controls in the next column according the width of the previous one... etc. Could there be a simpler solution? ---------------------------------------------------------------------- wp · 2014-01-08 08:20 Too strict layouts are always an issue, in Windows for example if you go to a PC running at 120 dpi instead of the usual 96 dpi. I'd use two left-aligned panels for the two button groups. Add the controls top-aligned and provide sufficient border around the controls to get the spacing that you want. Then, after changing language, iterate through the buttons on each panel and determine the longest button caption (Canvas.TextWidth). Set the width of the owning panel to that textwidth plus the borders around the button plus some pixels for spacing between caption and button border. ---------------------------------------------------------------------- CM630 · 2014-01-08 12:55 That's not much different from my idea, so I guess no one did anything ready like anchoring). I'll try to make an example and put it in the wiki. ---------------------------------------------------------------------- CM630 · 2014-05-12 06:44 Just to mention that there is a very serious bug in the Lazarus PO file support. When a string is flagged as fuzzy the original value shall be displayed, instead of the translated one, but Lazarus apps show „translated“ values. When I happen to find time for that I will check if it is the bugzilla, unless someone does it before me. ---------------------------------------------------------------------- sapper · 2014-05-18 09:23 Quote from: wp on December 19, 2013, 10:40:47 amTo make it clear: to have LCL strings translated you copy lclstrconsts.*.po to your languages folder, and then you can modify them in any way you want - LCL translations are completely coupled off of Lazarus. Unfortunately, there's a lot of common dialogs where strings are defined by the OS and cannot be changed that easily... Can you release a demo project for this. I have no success with this. I added an OpenDialog to the form and a button to execute it. I have copied lclstrconsts.de.po to the languages folder but opening the dialog with Deutsch selected the dialog caption is still English. If I run the project with parameter --lang de and open the dialog it has German caption but buttons "OK" and "Cancel" so I assume "OK" and "Cancel" do not change. ---------------------------------------------------------------------- wp · 2014-05-18 15:18 Quote Unfortunately, there's a lot of common dialogs where strings are defined by the OS and cannot be changed that easily...The same here. The problem is that the FileOpenDialog calls Windows resources which cannot be reached by the method presented here. Back in my Delphi days, I knew of Windows-only versions of the FileDialog where the strings could be replaced at run-time. Unfortunately, I don't find the links any more (www.torry.net?) ... So, if Windows-only is an aption, you'll have to spend some time with Google.