gnuGettext.pas 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910
  1. { *------------------------------------------------------------------------------
  2. GNU gettext translation system for Delphi, Kylix, C++ Builder and others.
  3. All parts of the translation system are kept in this unit.
  4. @author Lars B. Dybdahl and others
  5. ------------------------------------------------------------------------------- }
  6. unit gnugettext;
  7. (* ************************************************************ *)
  8. (* *)
  9. (* (C) Copyright by Lars B. Dybdahl and others *)
  10. (* E-mail: [email protected], phone +45 70201241 *)
  11. (* *)
  12. (* Contributors: Peter Thornqvist, Troy Wolbrink, *)
  13. (* Frank Andreas de Groot, Igor Siticov, *)
  14. (* Jacques Garcia Vazquez, Igor Gitman, *)
  15. (* Arvid Winkelsdorf *)
  16. (* *)
  17. (* See http://dybdahl.dk/dxgettext/ for more information *)
  18. (* *)
  19. (* ************************************************************ *)
  20. // Changes J. Rathlev (kontakt(a)rathlev-home.de)
  21. // see: JR - 2011-07-29 / 2012-09-10
  22. // All Delphi version related compiler switches removed - needs at least Delphi XE2
  23. // GetWindowsLanguage uses GetUserPreferredUILanguages (Sept. 2023)
  24. // Information about this file:
  25. // $LastChangedDate: 2024-08-24 $
  26. // Redistribution and use in source and binary forms, with or without
  27. // modification, are permitted provided that the following conditions are met:
  28. //
  29. // The names of any contributor may not be used to endorse or promote
  30. // products derived from this software without specific prior written permission.
  31. //
  32. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  33. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  34. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  35. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  36. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  37. // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  38. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  40. // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. interface
  43. // If the conditional define DXGETTEXTDEBUG is defined, debugging log is activated.
  44. // Use DefaultInstance.DebugLogToFile() to write the log to a file.
  45. { $define DXGETTEXTDEBUG }
  46. uses
  47. {$IFDEF MSWINDOWS}
  48. Winapi.Windows,
  49. {$ELSE}
  50. Libc,
  51. {$IFDEF FPC}
  52. CWString,
  53. {$ENDIF}
  54. {$ENDIF}
  55. System.Classes, System.StrUtils, System.SysUtils, System.TypInfo;
  56. (* *************************************************************************** *)
  57. (* *)
  58. (* MAIN API *)
  59. (* *)
  60. (* *************************************************************************** *)
  61. type
  62. {$IFNDEF UNICODE}
  63. UnicodeString = WideString;
  64. RawUtf8String = AnsiString;
  65. RawByteString = AnsiString;
  66. {$ELSE}
  67. RawUtf8String = RawByteString;
  68. {$ENDIF}
  69. DomainString = string;
  70. LanguageString = string;
  71. ComponentNameString = string;
  72. FilenameString = string;
  73. MsgIdString = UnicodeString;
  74. TranslatedUnicodeString = UnicodeString;
  75. // Main GNU gettext functions. See documentation for instructions on how to use them.
  76. function _(const szMsgId: MsgIdString): TranslatedUnicodeString;
  77. function gettext(const szMsgId: MsgIdString): TranslatedUnicodeString;
  78. function gettext_NoExtract(const szMsgId: MsgIdString): TranslatedUnicodeString;
  79. function gettext_NoOp(const szMsgId: MsgIdString): TranslatedUnicodeString;
  80. function dgettext(const szDomain: DomainString; const szMsgId: MsgIdString)
  81. : TranslatedUnicodeString;
  82. function dgettext_NoExtract(const szDomain: DomainString;
  83. const szMsgId: MsgIdString): TranslatedUnicodeString;
  84. function dngettext(const szDomain: DomainString;
  85. const singular, plural: MsgIdString; Number: longint)
  86. : TranslatedUnicodeString;
  87. function ngettext(const singular, plural: MsgIdString; Number: longint)
  88. : TranslatedUnicodeString;
  89. function ngettext_NoExtract(const singular, plural: MsgIdString;
  90. Number: longint): TranslatedUnicodeString;
  91. procedure textdomain(const szDomain: DomainString);
  92. function getcurrenttextdomain: DomainString;
  93. procedure bindtextdomain(const szDomain: DomainString;
  94. const szDirectory: FilenameString);
  95. // Set language to use
  96. procedure UseLanguage(LanguageCode: LanguageString);
  97. function GetCurrentLanguage: LanguageString;
  98. // Translates a component (form, frame etc.) to the currently selected language.
  99. // Put TranslateComponent(self) in the OnCreate event of all your forms.
  100. // See the manual for documentation on these functions
  101. type
  102. TTranslator = procedure(obj: TObject) of object;
  103. procedure TP_Ignore(AnObject: TObject; const name: ComponentNameString);
  104. procedure TP_IgnoreClass(IgnClass: TClass);
  105. procedure TP_IgnoreClassProperty(IgnClass: TClass;
  106. const propertyname: ComponentNameString);
  107. procedure TP_GlobalIgnoreClass(IgnClass: TClass);
  108. procedure TP_GlobalIgnoreClassProperty(IgnClass: TClass;
  109. const propertyname: ComponentNameString);
  110. procedure TP_GlobalHandleClass(HClass: TClass; Handler: TTranslator);
  111. procedure TranslateComponent(AnObject: TComponent;
  112. const textdomain: DomainString = '');
  113. procedure RetranslateComponent(AnObject: TComponent;
  114. const textdomain: DomainString = '');
  115. // Add more domains that resourcestrings can be extracted from. If a translation
  116. // is not found in the default domain, this domain will be searched, too.
  117. // This is useful for adding mo files for certain runtime libraries and 3rd
  118. // party component libraries
  119. procedure AddDomainForResourceString(const domain: DomainString);
  120. procedure RemoveDomainForResourceString(const domain: DomainString);
  121. procedure AddDomains(const Domains: array of DomainString);
  122. // Add more domains that component strings can be extracted from. If a translation
  123. // is not found in the default domain, this domain will be searched, too.
  124. // This is useful when an application inherits components from a 3rd
  125. // party component libraries
  126. procedure AddDomainForComponent(const domain: DomainString);
  127. procedure RemoveDomainForComponent(const domain: DomainString);
  128. // Unicode-enabled way to get resourcestrings, automatically translated
  129. // Use like this: ws:=LoadResStringW(@NameOfResourceString);
  130. function LoadResString(ResStringRec: PResStringRec): WideString;
  131. function LoadResStringW(ResStringRec: PResStringRec): UnicodeString;
  132. // This returns an empty string if not translated or translator name is not specified.
  133. function GetTranslatorNameAndEmail: TranslatedUnicodeString;
  134. (* *************************************************************************** *)
  135. (* *)
  136. (* ADVANCED FUNCTIONALITY *)
  137. (* *)
  138. (* *************************************************************************** *)
  139. const
  140. DefaultTextDomain = 'default';
  141. var
  142. ExecutableFilename: FilenameString;
  143. // This is set to paramstr(0) or the name of the DLL you are creating.
  144. const
  145. PreferExternal = True;
  146. // Set to true, to prefer external *.mo over embedded translation
  147. UseMemoryMappedFiles = True;
  148. // Set to False, to use the mo-file as independent copy in memory (you can update the file while it is in use)
  149. ReReadMoFileOnSameLanguage = True;
  150. // Set to True, to reread mo-file if the current language is selected again
  151. const
  152. // Subversion source code version control version information
  153. VCSVersion = '$LastChangedRevision: 220 $';
  154. type
  155. EGnuGettext = class(Exception);
  156. EGGProgrammingError = class(EGnuGettext);
  157. EGGComponentError = class(EGnuGettext);
  158. EGGIOError = class(EGnuGettext);
  159. EGGAnsi2WideConvError = class(EGnuGettext);
  160. // This function will turn resourcestring hooks on or off, eventually with BPL file support.
  161. // Please do not activate BPL file support when the package is in design mode.
  162. const
  163. AutoCreateHooks = True;
  164. procedure HookIntoResourceStrings(enabled: boolean = True;
  165. SupportPackages: boolean = false);
  166. (* *************************************************************************** *)
  167. (* *)
  168. (* CLASS based implementation. *)
  169. (* Use TGnuGettextInstance to have more than one language *)
  170. (* in your application at the same time *)
  171. (* *)
  172. (* *************************************************************************** *)
  173. type
  174. TOnDebugLine = Procedure(Sender: TObject; const Line: String;
  175. var Discard: boolean) of Object;
  176. // Set Discard to false if output should still go to ordinary debug log
  177. TGetPluralForm = function(Number: longint): Integer;
  178. TDebugLogger = procedure(Line: AnsiString) of object;
  179. { *------------------------------------------------------------------------------
  180. Handles .mo files, in separate files or inside the exe file.
  181. Don't use this class. It's for internal use.
  182. ------------------------------------------------------------------------------- }
  183. TMoFile = class
  184. /// Threadsafe. Only constructor and destructor are writing to memory
  185. private
  186. doswap: boolean;
  187. public
  188. Users: Integer;
  189. /// Reference count. If it reaches zero, this object should be destroyed.
  190. constructor Create(const filename: FilenameString; const Offset: int64;
  191. Size: int64; const xUseMemoryMappedFiles: boolean);
  192. destructor Destroy; override;
  193. function gettext(const msgid: RawUtf8String; var found: boolean)
  194. : RawUtf8String; // uses mo file and utf-8
  195. property isSwappedArchitecture: boolean read doswap;
  196. private
  197. N, O, T: Cardinal;
  198. /// Values defined at http://www.linuxselfhelp.com/gnu/gettext/html_chapter/gettext_6.html
  199. startindex, startstep: Integer;
  200. FUseMemoryMappedFiles: boolean;
  201. mo: THandle;
  202. momapping: THandle;
  203. momemoryHandle: PAnsiChar;
  204. momemory: PAnsiChar;
  205. function autoswap32(i: Cardinal): Cardinal;
  206. function CardinalInMem(baseptr: PAnsiChar; Offset: Cardinal): Cardinal;
  207. end;
  208. { *------------------------------------------------------------------------------
  209. Handles all issues regarding a specific domain.
  210. Don't use this class. It's for internal use.
  211. ------------------------------------------------------------------------------- }
  212. TDomain = class
  213. private
  214. enabled: boolean;
  215. vDirectory: FilenameString;
  216. procedure setDirectory(const dir: FilenameString);
  217. public
  218. DebugLogger: TDebugLogger;
  219. domain: DomainString;
  220. property Directory: FilenameString read vDirectory write setDirectory;
  221. constructor Create;
  222. destructor Destroy; override;
  223. // Set parameters
  224. procedure SetLanguageCode(const langcode: LanguageString);
  225. procedure SetFilename(const filename: FilenameString);
  226. // Bind this domain to a specific file
  227. // Get information
  228. procedure GetListOfLanguages(list: TStrings);
  229. function GetTranslationProperty(propertyname: ComponentNameString)
  230. : TranslatedUnicodeString;
  231. function gettext(const msgid: RawUtf8String): RawUtf8String;
  232. // uses mo file and utf-8
  233. private
  234. mofile: TMoFile;
  235. SpecificFilename: FilenameString;
  236. curlang: LanguageString;
  237. OpenHasFailedBefore: boolean;
  238. procedure OpenMoFile;
  239. procedure CloseMoFile;
  240. end;
  241. { *------------------------------------------------------------------------------
  242. Helper class for invoking events.
  243. ------------------------------------------------------------------------------- }
  244. TExecutable = class
  245. procedure Execute; virtual; abstract;
  246. end;
  247. { *------------------------------------------------------------------------------
  248. Interface to implement if you want to register as a language change listener
  249. ------------------------------------------------------------------------------- }
  250. IGnuGettextInstanceWhenNewLanguageListener = interface
  251. procedure WhenNewLanguage(const LanguageID: LanguageString);
  252. end;
  253. { *------------------------------------------------------------------------------
  254. The main translation engine.
  255. ------------------------------------------------------------------------------- }
  256. TGnuGettextInstance = class
  257. private
  258. fOnDebugLine: TOnDebugLine;
  259. public
  260. enabled: boolean;
  261. /// Set this to false to disable translations
  262. DesignTimeCodePage: Integer;
  263. /// See MultiByteToWideChar() in Win32 API for documentation
  264. constructor Create;
  265. destructor Destroy; override;
  266. procedure UseLanguage(LanguageCode: LanguageString);
  267. procedure GetListOfLanguages(const domain: DomainString; list: TStrings);
  268. // Puts list of language codes, for which there are translations in the specified domain, into list
  269. {$IFNDEF UNICODE}
  270. function gettext(const szMsgId: AnsiString): TranslatedUnicodeString;
  271. overload; virtual;
  272. function ngettext(const singular, plural: AnsiString; Number: longint)
  273. : TranslatedUnicodeString; overload; virtual;
  274. {$ENDIF}
  275. function gettext(const szMsgId: MsgIdString): TranslatedUnicodeString;
  276. overload; virtual;
  277. function gettext_NoExtract(const szMsgId: MsgIdString)
  278. : TranslatedUnicodeString;
  279. function gettext_NoOp(const szMsgId: MsgIdString): TranslatedUnicodeString;
  280. function ngettext(const singular, plural: MsgIdString; Number: longint)
  281. : TranslatedUnicodeString; overload; virtual;
  282. function ngettext_NoExtract(const singular, plural: MsgIdString;
  283. Number: longint): TranslatedUnicodeString;
  284. function GetCurrentLanguage: LanguageString;
  285. function GetTranslationProperty(const propertyname: ComponentNameString)
  286. : TranslatedUnicodeString;
  287. function GetTranslatorNameAndEmail: TranslatedUnicodeString;
  288. // Form translation tools, these are not threadsafe. All TP_ procs must be called just before TranslateProperites()
  289. procedure TP_Ignore(AnObject: TObject; const name: ComponentNameString);
  290. procedure TP_IgnoreClass(IgnClass: TClass);
  291. procedure TP_IgnoreClassProperty(IgnClass: TClass;
  292. propertyname: ComponentNameString);
  293. procedure TP_GlobalIgnoreClass(IgnClass: TClass);
  294. procedure TP_GlobalIgnoreClassProperty(IgnClass: TClass;
  295. propertyname: ComponentNameString);
  296. procedure TP_GlobalHandleClass(HClass: TClass; Handler: TTranslator);
  297. procedure TranslateProperties(AnObject: TObject;
  298. textdomain: DomainString = '');
  299. procedure TranslateComponent(AnObject: TComponent;
  300. const textdomain: DomainString = '');
  301. procedure RetranslateComponent(AnObject: TComponent;
  302. const textdomain: DomainString = '');
  303. // Multi-domain functions
  304. {$IFNDEF UNICODE}
  305. function dgettext(const szDomain: DomainString; const szMsgId: AnsiString)
  306. : TranslatedUnicodeString; overload; virtual;
  307. function dngettext(const szDomain: DomainString;
  308. const singular, plural: AnsiString; Number: longint)
  309. : TranslatedUnicodeString; overload; virtual;
  310. {$ENDIF}
  311. function dgettext(const szDomain: DomainString; const szMsgId: MsgIdString)
  312. : TranslatedUnicodeString; overload; virtual;
  313. function dgettext_NoExtract(const szDomain: DomainString;
  314. const szMsgId: MsgIdString): TranslatedUnicodeString;
  315. function dngettext(const szDomain: DomainString;
  316. const singular, plural: MsgIdString; Number: longint)
  317. : TranslatedUnicodeString; overload; virtual;
  318. function dngettext_NoExtract(const szDomain: DomainString;
  319. const singular, plural: MsgIdString; Number: longint)
  320. : TranslatedUnicodeString;
  321. procedure textdomain(const szDomain: DomainString);
  322. function getcurrenttextdomain: DomainString;
  323. procedure bindtextdomain(const szDomain: DomainString;
  324. const szDirectory: FilenameString);
  325. procedure bindtextdomainToFile(const szDomain: DomainString;
  326. const filename: FilenameString);
  327. // Also works with files embedded in exe file
  328. // Windows API functions
  329. function LoadResString(ResStringRec: PResStringRec): UnicodeString;
  330. // Output all log info to this file. This may only be called once.
  331. procedure DebugLogToFile(const filename: FilenameString;
  332. append: boolean = false);
  333. procedure DebugLogPause(PauseEnabled: boolean);
  334. property OnDebugLine: TOnDebugLine read fOnDebugLine write fOnDebugLine;
  335. // If set, all debug output goes here
  336. {$IFNDEF UNICODE}
  337. // Conversion according to design-time character set
  338. function ansi2wideDTCP(const s: AnsiString): MsgIdString;
  339. // Convert using Design Time Code Page
  340. {$ENDIF}
  341. procedure RegisterWhenNewLanguageListener
  342. (Listener: IGnuGettextInstanceWhenNewLanguageListener);
  343. procedure UnregisterWhenNewLanguageListener
  344. (Listener: IGnuGettextInstanceWhenNewLanguageListener);
  345. protected
  346. procedure TranslateStrings(sl: TStrings; const textdomain: DomainString);
  347. // Override these three, if you want to inherited from this class
  348. // to create a new class that handles other domain and language dependent
  349. // issues
  350. procedure WhenNewLanguage(const LanguageID: LanguageString); virtual;
  351. // Override to know when language changes
  352. procedure WhenNewDomain(const textdomain: DomainString); virtual;
  353. // Override to know when text domain changes. Directory is purely informational
  354. procedure WhenNewDomainDirectory(const textdomain: DomainString;
  355. const Directory: FilenameString); virtual;
  356. // Override to know when any text domain's directory changes. It won't be called if a domain is fixed to a specific file.
  357. private
  358. curlang: LanguageString;
  359. curGetPluralForm: TGetPluralForm;
  360. curmsgdomain: DomainString;
  361. savefileCS: TMultiReadExclusiveWriteSynchronizer;
  362. savefile: TextFile;
  363. savememory: TStringList;
  364. DefaultDomainDirectory: FilenameString;
  365. domainlist: TStringList;
  366. /// List of domain names. Objects are TDomain.
  367. TP_IgnoreList: TStringList;
  368. /// Temporary list, reset each time TranslateProperties is called
  369. TP_ClassHandling: TList;
  370. /// Items are TClassMode. If a is derived from b, a comes first
  371. TP_GlobalClassHandling: TList;
  372. /// Items are TClassMode. If a is derived from b, a comes first
  373. TP_Retranslator: TExecutable;
  374. /// Cast this to TTP_Retranslator
  375. fWhenNewLanguageListeners: TInterfaceList;
  376. /// List of all registered WhenNewLanguage listeners
  377. {$IFDEF DXGETTEXTDEBUG}
  378. DebugLogCS: TMultiReadExclusiveWriteSynchronizer;
  379. DebugLog: TStream;
  380. DebugLogOutputPaused: boolean;
  381. {$ENDIF}
  382. function TP_CreateRetranslator: TExecutable; // Must be freed by caller!
  383. procedure FreeTP_ClassHandlingItems;
  384. {$IFDEF DXGETTEXTDEBUG}
  385. procedure DebugWriteln(Line: AnsiString);
  386. {$ENDIF}
  387. procedure TranslateProperty(AnObject: TObject; PropInfo: PPropInfo;
  388. TodoList: TStrings; const textdomain: DomainString);
  389. function Getdomain(const domain: DomainString;
  390. const DefaultDomainDirectory: FilenameString;
  391. const curlang: LanguageString): TDomain;
  392. // Translates a single property of an object
  393. end;
  394. var
  395. DefaultInstance: TGnuGettextInstance;
  396. /// Default instance of the main API for singlethreaded applications.
  397. implementation
  398. {$IFNDEF MSWINDOWS}
  399. {$IFNDEF LINUX}
  400. 'This version of gnugettext.pas is only meant to be compiled with Kylix 3,'
  401. 'Delphi 6, Delphi 7 and later versions. If you use other versions, please'
  402. 'get the gnugettext.pas version from the Delphi 5 directory.'
  403. {$ENDIF}
  404. {$ENDIF}
  405. (* ************************************************************************ *)
  406. // Some comments on the implementation:
  407. // This unit should be independent of other units where possible.
  408. // It should have a small footprint in any way.
  409. (* ************************************************************************ *)
  410. // TMultiReadExclusiveWriteSynchronizer is used instead of TCriticalSection
  411. // because it makes this unit independent of the SyncObjs unit
  412. (* ************************************************************************ *)
  413. {$B-,R+,I+,Q+}
  414. type TTP_RetranslatorItem = class obj: TObject;
  415. Propname:
  416. ComponentNameString;
  417. OldValue:
  418. TranslatedUnicodeString;
  419. end;
  420. TTP_Retranslator = class(TExecutable)textdomain: DomainString;
  421. Instance:
  422. TGnuGettextInstance;
  423. constructor Create;
  424. destructor Destroy; override;
  425. procedure Remember(obj: TObject; Propname: ComponentNameString;
  426. OldValue: TranslatedUnicodeString);
  427. procedure Execute; override;
  428. private
  429. list: TList;
  430. end;
  431. TEmbeddedFileInfo = class Offset, Size: int64;
  432. end;
  433. TFileLocator = class
  434. // This class finds files even when embedded inside executable
  435. constructor Create;
  436. destructor Destroy;
  437. override;
  438. function FindSignaturePos(const signature: RawByteString;
  439. str: TFileStream): int64;
  440. procedure Analyze; // List files embedded inside executable
  441. function FileExists(filename: FilenameString): boolean;
  442. function GetMoFile(filename: FilenameString;
  443. DebugLogger: TDebugLogger): TMoFile;
  444. procedure ReleaseMoFile(mofile: TMoFile);
  445. private
  446. basedirectory: FilenameString;
  447. filelist: TStringList;
  448. // Objects are TEmbeddedFileInfo. Filenames are relative to .exe file
  449. MoFilesCS: TMultiReadExclusiveWriteSynchronizer;
  450. MoFiles: TStringList;
  451. // Objects are filenames+offset, objects are TMoFile
  452. function ReadInt64(str: TStream): int64;
  453. end;
  454. TGnuGettextComponentMarker = class(TComponent)public LastLanguage
  455. : LanguageString;
  456. Retranslator: TExecutable;
  457. destructor Destroy;
  458. override;
  459. end;
  460. TClassMode = class HClass: TClass;
  461. SpecialHandler: TTranslator;
  462. PropertiesToIgnore: TStringList; // This is ignored if Handler is set
  463. constructor Create;
  464. destructor Destroy;
  465. override;
  466. end;
  467. TRStrinfo = record strlength, stroffset: Cardinal;
  468. end;
  469. TStrInfoArr = array [0 .. 10000000] of TRStrinfo;
  470. PStrInfoArr = ^TStrInfoArr;
  471. TCharArray5 = array [0 .. 4] of ansichar;
  472. THook = // Replaces a runtime library procedure with a custom procedure
  473. class public constructor Create(OldProcedure, NewProcedure: pointer;
  474. FollowJump: boolean = false);
  475. destructor Destroy;
  476. override; // Restores unhooked state
  477. procedure Reset(FollowJump: boolean = false);
  478. // Disables and picks up patch points again
  479. procedure Disable;
  480. procedure Enable;
  481. private
  482. oldproc, newproc: pointer;
  483. Patch: TCharArray5;
  484. Original: TCharArray5;
  485. PatchPosition: PAnsiChar;
  486. procedure Shutdown;
  487. // Same as destroy, except that object is not destroyed
  488. end;
  489. var
  490. // System information
  491. Win32PlatformIsUnicode: boolean = false;
  492. // Information about files embedded inside .exe file
  493. FileLocator: TFileLocator;
  494. // Hooks into runtime library functions
  495. ResourceStringDomainListCS: TMultiReadExclusiveWriteSynchronizer;
  496. ResourceStringDomainList: TStringList;
  497. ComponentDomainListCS: TMultiReadExclusiveWriteSynchronizer;
  498. ComponentDomainList: TStringList;
  499. HookLoadResString: THook;
  500. HookLoadStr: THook;
  501. HookFmtLoadStr: THook;
  502. function GGGetEnvironmentVariable(const name: WideString): WideString;
  503. var
  504. Len: Integer;
  505. W: WideString;
  506. begin
  507. Result := '';
  508. SetLength(W, 1);
  509. Len := GetEnvironmentVariableW(PWideChar(Name), PWideChar(W), 1);
  510. if Len > 0 then
  511. begin
  512. SetLength(Result, Len - 1);
  513. GetEnvironmentVariableW(PWideChar(Name), PWideChar(Result), Len);
  514. end;
  515. end;
  516. function StripCRRawMsgId(s: RawUtf8String): RawUtf8String;
  517. var
  518. i: Integer;
  519. begin
  520. i := 1;
  521. while i <= length(s) do
  522. begin
  523. if s[i] = #13 then
  524. delete(s, i, 1)
  525. else
  526. inc(i);
  527. end;
  528. Result := s;
  529. end;
  530. function EnsureLineBreakInTranslatedString(s: RawUtf8String)
  531. : RawUtf8String;
  532. {$IFDEF MSWINDOWS}
  533. var
  534. i: Integer;
  535. {$ENDIF}
  536. begin
  537. {$IFDEF MSWINDOWS}
  538. Assert(sLinebreak = AnsiString(#13#10));
  539. i := 1;
  540. while i <= length(s) do
  541. begin
  542. if (s[i] = #10) and (MidStr(s, i - 1, 1) <> #13) then
  543. begin
  544. insert(#13, s, i);
  545. inc(i, 2);
  546. end
  547. else
  548. inc(i);
  549. end;
  550. {$ENDIF}
  551. Result := s;
  552. end;
  553. function IsWriteProp(Info: PPropInfo): boolean;
  554. begin
  555. Result := Assigned(Info) and (Info^.SetProc <> nil);
  556. end;
  557. function ResourceStringGettext(msgid: MsgIdString)
  558. : TranslatedUnicodeString;
  559. var
  560. i: Integer;
  561. begin
  562. if (msgid = '') or (ResourceStringDomainListCS = nil) then
  563. begin
  564. // This only happens during very complicated program startups that fail,
  565. // or when Msgid=''
  566. Result := msgid;
  567. exit;
  568. end;
  569. ResourceStringDomainListCS.BeginRead;
  570. try
  571. for i := 0 to ResourceStringDomainList.Count - 1 do
  572. begin
  573. Result := dgettext(ResourceStringDomainList.Strings[i], msgid);
  574. if Result <> msgid then
  575. break;
  576. end;
  577. finally
  578. ResourceStringDomainListCS.EndRead;
  579. end;
  580. end;
  581. function ComponentGettext(msgid: MsgIdString;
  582. Instance: TGnuGettextInstance = nil): TranslatedUnicodeString;
  583. var
  584. i: Integer;
  585. begin
  586. if (msgid = '') or (ComponentDomainListCS = nil) then
  587. begin
  588. // This only happens during very complicated program startups that fail,
  589. // or when Msgid=''
  590. Result := msgid;
  591. exit;
  592. end;
  593. ComponentDomainListCS.BeginRead;
  594. try
  595. for i := 0 to ComponentDomainList.Count - 1 do
  596. begin
  597. if Assigned(Instance) then
  598. Result := Instance.dgettext
  599. (ComponentDomainList.Strings[i], msgid)
  600. else
  601. Result := dgettext(ComponentDomainList.Strings[i], msgid);
  602. if Result <> msgid then
  603. break;
  604. end;
  605. finally
  606. ComponentDomainListCS.EndRead;
  607. end;
  608. end;
  609. function gettext(const szMsgId: MsgIdString): TranslatedUnicodeString;
  610. begin
  611. Result := DefaultInstance.gettext(szMsgId);
  612. end;
  613. function gettext_NoExtract(const szMsgId: MsgIdString)
  614. : TranslatedUnicodeString;
  615. begin
  616. // This one is very useful for translating text in variables.
  617. // This can sometimes be necessary, and by using this function,
  618. // the source code scanner will not trigger warnings.
  619. Result := gettext(szMsgId);
  620. end;
  621. function gettext_NoOp(const szMsgId: MsgIdString)
  622. : TranslatedUnicodeString;
  623. begin
  624. // *** With this function Strings can be added to the po-file without beeing
  625. // ResourceStrings (dxgettext will add the string and this function will
  626. // return it without a change)
  627. // see gettext manual
  628. // 4.7 - Special Cases of Translatable Strings
  629. // http://www.gnu.org/software/hello/manual/gettext/Special-cases.html#Special-cases
  630. Result := DefaultInstance.gettext_NoOp(szMsgId);
  631. end;
  632. { *------------------------------------------------------------------------------
  633. This is the main translation procedure used in programs. It takes a parameter,
  634. looks it up in the translation dictionary, and returns the translation.
  635. If no translation is found, the parameter is returned.
  636. @param szMsgId The text, that should be displayed if no translation is found.
  637. ------------------------------------------------------------------------------- }
  638. function _(const szMsgId: MsgIdString): TranslatedUnicodeString;
  639. begin
  640. Result := DefaultInstance.gettext(szMsgId);
  641. end;
  642. { *------------------------------------------------------------------------------
  643. Translates a text, using a specified translation domain.
  644. If no translation is found, the parameter is returned.
  645. @param szDomain Which translation domain that should be searched for a translation.
  646. @param szMsgId The text, that should be displayed if no translation is found.
  647. ------------------------------------------------------------------------------- }
  648. function dgettext(const szDomain: DomainString;
  649. const szMsgId: MsgIdString): TranslatedUnicodeString;
  650. begin
  651. Result := DefaultInstance.dgettext(szDomain, szMsgId);
  652. end;
  653. function dgettext_NoExtract(const szDomain: DomainString;
  654. const szMsgId: MsgIdString): TranslatedUnicodeString;
  655. begin
  656. // This one is very useful for translating text in variables.
  657. // This can sometimes be necessary, and by using this function,
  658. // the source code scanner will not trigger warnings.
  659. Result := dgettext(szDomain, szMsgId);
  660. end;
  661. function dngettext(const szDomain: DomainString;
  662. const singular, plural: MsgIdString; Number: longint)
  663. : TranslatedUnicodeString;
  664. begin
  665. Result := DefaultInstance.dngettext(szDomain, singular,
  666. plural, Number);
  667. end;
  668. function ngettext(const singular, plural: MsgIdString; Number: longint)
  669. : TranslatedUnicodeString;
  670. begin
  671. Result := DefaultInstance.ngettext(singular, plural, Number);
  672. end;
  673. function ngettext_NoExtract(const singular, plural: MsgIdString;
  674. Number: longint): TranslatedUnicodeString;
  675. begin
  676. // This one is very useful for translating text in variables.
  677. // This can sometimes be necessary, and by using this function,
  678. // the source code scanner will not trigger warnings.
  679. Result := ngettext(singular, plural, Number);
  680. end;
  681. procedure textdomain(const szDomain: DomainString);
  682. begin
  683. DefaultInstance.textdomain(szDomain);
  684. end;
  685. procedure SetGettextEnabled(enabled: boolean);
  686. begin
  687. DefaultInstance.enabled := enabled;
  688. end;
  689. function getcurrenttextdomain: DomainString;
  690. begin
  691. Result := DefaultInstance.getcurrenttextdomain;
  692. end;
  693. procedure bindtextdomain(const szDomain: DomainString;
  694. const szDirectory: FilenameString);
  695. begin
  696. DefaultInstance.bindtextdomain(szDomain, szDirectory);
  697. end;
  698. procedure TP_Ignore(AnObject: TObject; const name: FilenameString);
  699. begin
  700. DefaultInstance.TP_Ignore(AnObject, name);
  701. end;
  702. procedure TP_GlobalIgnoreClass(IgnClass: TClass);
  703. begin
  704. DefaultInstance.TP_GlobalIgnoreClass(IgnClass);
  705. end;
  706. procedure TP_IgnoreClass(IgnClass: TClass);
  707. begin
  708. DefaultInstance.TP_IgnoreClass(IgnClass);
  709. end;
  710. procedure TP_IgnoreClassProperty(IgnClass: TClass;
  711. const propertyname: ComponentNameString);
  712. begin
  713. DefaultInstance.TP_IgnoreClassProperty(IgnClass, propertyname);
  714. end;
  715. procedure TP_GlobalIgnoreClassProperty(IgnClass: TClass;
  716. const propertyname: ComponentNameString);
  717. begin
  718. DefaultInstance.TP_GlobalIgnoreClassProperty(IgnClass, propertyname);
  719. end;
  720. procedure TP_GlobalHandleClass(HClass: TClass; Handler: TTranslator);
  721. begin
  722. DefaultInstance.TP_GlobalHandleClass(HClass, Handler);
  723. end;
  724. procedure TranslateComponent(AnObject: TComponent;
  725. const textdomain: DomainString = '');
  726. begin
  727. DefaultInstance.TranslateComponent(AnObject, textdomain);
  728. end;
  729. procedure RetranslateComponent(AnObject: TComponent;
  730. const textdomain: DomainString = '');
  731. begin
  732. DefaultInstance.RetranslateComponent(AnObject, textdomain);
  733. end;
  734. {$IFDEF MSWINDOWS}
  735. // These constants are only used in Windows 95
  736. // Thanks to Frank Andreas de Groot for this table
  737. const
  738. IDAfrikaans = $0436;
  739. IDAlbanian = $041C;
  740. IDArabicAlgeria = $1401;
  741. IDArabicBahrain = $3C01;
  742. IDArabicEgypt = $0C01;
  743. IDArabicIraq = $0801;
  744. IDArabicJordan = $2C01;
  745. IDArabicKuwait = $3401;
  746. IDArabicLebanon = $3001;
  747. IDArabicLibya = $1001;
  748. IDArabicMorocco = $1801;
  749. IDArabicOman = $2001;
  750. IDArabicQatar = $4001;
  751. IDArabic = $0401;
  752. IDArabicSyria = $2801;
  753. IDArabicTunisia = $1C01;
  754. IDArabicUAE = $3801;
  755. IDArabicYemen = $2401;
  756. IDArmenian = $042B;
  757. IDAssamese = $044D;
  758. IDAzeriCyrillic = $082C;
  759. IDAzeriLatin = $042C;
  760. IDBasque = $042D;
  761. IDByelorussian = $0423;
  762. IDBengali = $0445;
  763. IDBulgarian = $0402;
  764. IDBurmese = $0455;
  765. IDCatalan = $0403;
  766. IDChineseHongKong = $0C04;
  767. IDChineseMacao = $1404;
  768. IDSimplifiedChinese = $0804;
  769. IDChineseSingapore = $1004;
  770. IDTraditionalChinese = $0404;
  771. IDCroatian = $041A;
  772. IDCzech = $0405;
  773. IDDanish = $0406;
  774. IDBelgianDutch = $0813;
  775. IDDutch = $0413;
  776. IDEnglishAUS = $0C09;
  777. IDEnglishBelize = $2809;
  778. IDEnglishCanadian = $1009;
  779. IDEnglishCaribbean = $2409;
  780. IDEnglishIreland = $1809;
  781. IDEnglishJamaica = $2009;
  782. IDEnglishNewZealand = $1409;
  783. IDEnglishPhilippines = $3409;
  784. IDEnglishSouthAfrica = $1C09;
  785. IDEnglishTrinidad = $2C09;
  786. IDEnglishUK = $0809;
  787. IDEnglishUS = $0409;
  788. IDEnglishZimbabwe = $3009;
  789. IDEstonian = $0425;
  790. IDFaeroese = $0438;
  791. IDFarsi = $0429;
  792. IDFinnish = $040B;
  793. IDBelgianFrench = $080C;
  794. IDFrenchCameroon = $2C0C;
  795. IDFrenchCanadian = $0C0C;
  796. IDFrenchCotedIvoire = $300C;
  797. IDFrench = $040C;
  798. IDFrenchLuxembourg = $140C;
  799. IDFrenchMali = $340C;
  800. IDFrenchMonaco = $180C;
  801. IDFrenchReunion = $200C;
  802. IDFrenchSenegal = $280C;
  803. IDSwissFrench = $100C;
  804. IDFrenchWestIndies = $1C0C;
  805. IDFrenchZaire = $240C;
  806. IDFrisianNetherlands = $0462;
  807. IDGaelicIreland = $083C;
  808. IDGaelicScotland = $043C;
  809. IDGalician = $0456;
  810. IDGeorgian = $0437;
  811. IDGermanAustria = $0C07;
  812. IDGerman = $0407;
  813. IDGermanLiechtenstein = $1407;
  814. IDGermanLuxembourg = $1007;
  815. IDSwissGerman = $0807;
  816. IDGreek = $0408;
  817. IDGujarati = $0447;
  818. IDHebrew = $040D;
  819. IDHindi = $0439;
  820. IDHungarian = $040E;
  821. IDIcelandic = $040F;
  822. IDIndonesian = $0421;
  823. IDItalian = $0410;
  824. IDSwissItalian = $0810;
  825. IDJapanese = $0411;
  826. IDKannada = $044B;
  827. IDKashmiri = $0460;
  828. IDKazakh = $043F;
  829. IDKhmer = $0453;
  830. IDKirghiz = $0440;
  831. IDKonkani = $0457;
  832. IDKorean = $0412;
  833. IDLao = $0454;
  834. IDLatvian = $0426;
  835. IDLithuanian = $0427;
  836. IDMacedonian = $042F;
  837. IDMalaysian = $043E;
  838. IDMalayBruneiDarussalam = $083E;
  839. IDMalayalam = $044C;
  840. IDMaltese = $043A;
  841. IDManipuri = $0458;
  842. IDMarathi = $044E;
  843. IDMongolian = $0450;
  844. IDNepali = $0461;
  845. IDNorwegianBokmol = $0414;
  846. IDNorwegianNynorsk = $0814;
  847. IDOriya = $0448;
  848. IDPolish = $0415;
  849. IDBrazilianPortuguese = $0416;
  850. IDPortuguese = $0816;
  851. IDPunjabi = $0446;
  852. IDRhaetoRomanic = $0417;
  853. IDRomanianMoldova = $0818;
  854. IDRomanian = $0418;
  855. IDRussianMoldova = $0819;
  856. IDRussian = $0419;
  857. IDSamiLappish = $043B;
  858. IDSanskrit = $044F;
  859. IDSerbianCyrillic = $0C1A;
  860. IDSerbianLatin = $081A;
  861. IDSesotho = $0430;
  862. IDSindhi = $0459;
  863. IDSlovak = $041B;
  864. IDSlovenian = $0424;
  865. IDSorbian = $042E;
  866. IDSpanishArgentina = $2C0A;
  867. IDSpanishBolivia = $400A;
  868. IDSpanishChile = $340A;
  869. IDSpanishColombia = $240A;
  870. IDSpanishCostaRica = $140A;
  871. IDSpanishDominicanRepublic = $1C0A;
  872. IDSpanishEcuador = $300A;
  873. IDSpanishElSalvador = $440A;
  874. IDSpanishGuatemala = $100A;
  875. IDSpanishHonduras = $480A;
  876. IDMexicanSpanish = $080A;
  877. IDSpanishNicaragua = $4C0A;
  878. IDSpanishPanama = $180A;
  879. IDSpanishParaguay = $3C0A;
  880. IDSpanishPeru = $280A;
  881. IDSpanishPuertoRico = $500A;
  882. IDSpanishModernSort = $0C0A;
  883. IDSpanish = $040A;
  884. IDSpanishUruguay = $380A;
  885. IDSpanishVenezuela = $200A;
  886. IDSutu = $0430;
  887. IDSwahili = $0441;
  888. IDSwedishFinland = $081D;
  889. IDSwedish = $041D;
  890. IDTajik = $0428;
  891. IDTamil = $0449;
  892. IDTatar = $0444;
  893. IDTelugu = $044A;
  894. IDThai = $041E;
  895. IDTibetan = $0451;
  896. IDTsonga = $0431;
  897. IDTswana = $0432;
  898. IDTurkish = $041F;
  899. IDTurkmen = $0442;
  900. IDUkrainian = $0422;
  901. IDUrdu = $0420;
  902. IDUzbekCyrillic = $0843;
  903. IDUzbekLatin = $0443;
  904. IDVenda = $0433;
  905. IDVietnamese = $042A;
  906. IDWelsh = $0452;
  907. IDXhosa = $0434;
  908. IDZulu = $0435;
  909. function GetWindowsLanguage: WideString;
  910. var
  911. langid, N, pc: Cardinal;
  912. buf: array of Char;
  913. langcode: WideString;
  914. CountryName: array [0 .. 4] of widechar;
  915. LanguageName: array [0 .. 4] of widechar;
  916. works: boolean;
  917. begin
  918. if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 6)
  919. then
  920. begin
  921. pc := 0; // Retrieve the UI language (not the localeinfo) JR - Sept. 2023
  922. works := GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @N, nil,
  923. @pc); // available since Vista
  924. if works then
  925. begin
  926. SetLength(buf, pc);
  927. works := GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, @N,
  928. @buf[0], @pc);
  929. if works then
  930. langcode := ReplaceStr(PChar(@buf[0]), '-', '_');
  931. buf := nil;
  932. end;
  933. end
  934. else
  935. begin // XP and older
  936. // The return value of GetLocaleInfo is compared with 3 = 2 characters and a zero
  937. works := 3 = GetLocaleInfoW(LOCALE_USER_DEFAULT,
  938. LOCALE_SISO639LANGNAME, LanguageName, SizeOf(LanguageName));
  939. works := works and
  940. (3 = GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
  941. CountryName, SizeOf(CountryName)));
  942. if works then
  943. begin
  944. // Windows 98, Me, NT4, 2000, XP and newer
  945. langcode := PWideChar(@(LanguageName[0]));
  946. if lowercase(langcode) = 'no' then
  947. langcode := 'nb';
  948. langcode := langcode + '_' + PWideChar(@CountryName[0]);
  949. end;
  950. end;
  951. if not works then
  952. begin
  953. // This part should only happen on Windows 95.
  954. langid := GetThreadLocale;
  955. case langid of
  956. IDBelgianDutch:
  957. langcode := 'nl_BE';
  958. IDBelgianFrench:
  959. langcode := 'fr_BE';
  960. IDBrazilianPortuguese:
  961. langcode := 'pt_BR';
  962. IDDanish:
  963. langcode := 'da_DK';
  964. IDDutch:
  965. langcode := 'nl_NL';
  966. IDEnglishUK:
  967. langcode := 'en_GB';
  968. IDEnglishUS:
  969. langcode := 'en_US';
  970. IDFinnish:
  971. langcode := 'fi_FI';
  972. IDFrench:
  973. langcode := 'fr_FR';
  974. IDFrenchCanadian:
  975. langcode := 'fr_CA';
  976. IDGerman:
  977. langcode := 'de_DE';
  978. IDGermanLuxembourg:
  979. langcode := 'de_LU';
  980. IDGreek:
  981. langcode := 'el_GR';
  982. IDIcelandic:
  983. langcode := 'is_IS';
  984. IDItalian:
  985. langcode := 'it_IT';
  986. IDKorean:
  987. langcode := 'ko_KO';
  988. IDNorwegianBokmol:
  989. langcode := 'nb_NO';
  990. IDNorwegianNynorsk:
  991. langcode := 'nn_NO';
  992. IDPolish:
  993. langcode := 'pl_PL';
  994. IDPortuguese:
  995. langcode := 'pt_PT';
  996. IDRussian:
  997. langcode := 'ru_RU';
  998. IDSpanish, IDSpanishModernSort:
  999. langcode := 'es_ES';
  1000. IDSwedish:
  1001. langcode := 'sv_SE';
  1002. IDSwedishFinland:
  1003. langcode := 'sv_FI';
  1004. else
  1005. langcode := 'C';
  1006. end;
  1007. end;
  1008. Result := langcode;
  1009. end;
  1010. {$ENDIF}
  1011. {$IFNDEF UNICODE}
  1012. function LoadResStringA(ResStringRec: PResStringRec): AnsiString;
  1013. begin
  1014. Result := DefaultInstance.LoadResString(ResStringRec);
  1015. end;
  1016. {$ENDIF}
  1017. function GetTranslatorNameAndEmail: TranslatedUnicodeString;
  1018. begin
  1019. Result := DefaultInstance.GetTranslatorNameAndEmail;
  1020. end;
  1021. procedure UseLanguage(LanguageCode: LanguageString);
  1022. begin
  1023. DefaultInstance.UseLanguage(LanguageCode);
  1024. end;
  1025. type
  1026. PStrData = ^TStrData;
  1027. TStrData = record
  1028. Ident: Integer;
  1029. str: String;
  1030. end;
  1031. function SysUtilsEnumStringModules(Instance: HINST;
  1032. Data: pointer): boolean;
  1033. {$IFDEF MSWINDOWS}
  1034. var
  1035. Buffer: array [0 .. 1023] of Char;
  1036. // WideChar in Delphi 2008, AnsiChar before that
  1037. begin
  1038. with PStrData(Data)^ do
  1039. begin
  1040. SetString(str, Buffer, LoadString(Instance, Ident, @Buffer[0],
  1041. SizeOf(Buffer)));
  1042. Result := str = '';
  1043. end;
  1044. end;
  1045. {$ENDIF}
  1046. {$IFDEF LINUX}
  1047. var
  1048. rs: TResStringRec;
  1049. Module: HModule;
  1050. begin
  1051. Module := Instance;
  1052. rs.Module := @Module;
  1053. with PStrData(Data)^ do
  1054. begin
  1055. rs.Identifier := Ident;
  1056. str := System.LoadResString(@rs);
  1057. Result := str = '';
  1058. end;
  1059. end;
  1060. {$ENDIF}
  1061. function SysUtilsFindStringResource(Ident: NativeInt): string;
  1062. var
  1063. StrData: TStrData;
  1064. begin
  1065. StrData.Ident := Ident;
  1066. StrData.str := '';
  1067. EnumResourceModules(SysUtilsEnumStringModules, @StrData);
  1068. Result := StrData.str;
  1069. end;
  1070. function SysUtilsLoadStr(Ident: Integer): string;
  1071. begin
  1072. {$IFDEF DXGETTEXTDEBUG}
  1073. DefaultInstance.DebugWriteln('Sysutils.LoadRes(' + IntToStr(Ident) +
  1074. ') called');
  1075. {$ENDIF}
  1076. Result := ResourceStringGettext(SysUtilsFindStringResource(Ident));
  1077. end;
  1078. function SysUtilsFmtLoadStr(Ident: Integer;
  1079. const Args: array of const): string;
  1080. begin
  1081. {$IFDEF DXGETTEXTDEBUG}
  1082. DefaultInstance.DebugWriteln('Sysutils.FmtLoadRes(' + IntToStr(Ident) +
  1083. ',Args) called');
  1084. {$ENDIF}
  1085. FmtStr(Result, ResourceStringGettext(SysUtilsFindStringResource
  1086. (Ident)), Args);
  1087. end;
  1088. function LoadResString(ResStringRec: PResStringRec): WideString;
  1089. begin
  1090. Result := DefaultInstance.LoadResString(ResStringRec);
  1091. end;
  1092. function LoadResStringW(ResStringRec: PResStringRec): UnicodeString;
  1093. begin
  1094. Result := DefaultInstance.LoadResString(ResStringRec);
  1095. end;
  1096. function GetCurrentLanguage: LanguageString;
  1097. begin
  1098. Result := DefaultInstance.GetCurrentLanguage;
  1099. end;
  1100. { TDomain }
  1101. procedure TDomain.CloseMoFile;
  1102. begin
  1103. if mofile <> nil then
  1104. begin
  1105. FileLocator.ReleaseMoFile(mofile);
  1106. mofile := nil;
  1107. end;
  1108. OpenHasFailedBefore := false;
  1109. end;
  1110. destructor TDomain.Destroy;
  1111. begin
  1112. CloseMoFile;
  1113. inherited;
  1114. end;
  1115. {$IFDEF mswindows}
  1116. function GetLastWinError: WideString;
  1117. var
  1118. errcode: Cardinal;
  1119. begin
  1120. SetLength(Result, 2000);
  1121. errcode := GetLastError();
  1122. FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, nil, errcode, 0,
  1123. PWideChar(Result), 2000, nil);
  1124. Result := PWideChar(Result);
  1125. end;
  1126. {$ENDIF}
  1127. procedure TDomain.OpenMoFile;
  1128. var
  1129. filename: FilenameString;
  1130. begin
  1131. // Check if it is already open
  1132. if mofile <> nil then
  1133. exit;
  1134. // Check if it has been attempted to open the file before
  1135. if OpenHasFailedBefore then
  1136. exit;
  1137. if SpecificFilename <> '' then
  1138. begin
  1139. filename := SpecificFilename;
  1140. {$IFDEF DXGETTEXTDEBUG}
  1141. DebugLogger('Domain ' + domain + ' is bound to specific file ' +
  1142. filename);
  1143. {$ENDIF}
  1144. end
  1145. else
  1146. begin
  1147. filename := Directory + curlang + PathDelim + 'LC_MESSAGES' +
  1148. PathDelim + domain + '.mo';
  1149. if (not FileLocator.FileExists(filename)) and
  1150. (not FileExists(filename)) then
  1151. begin
  1152. {$IFDEF DXGETTEXTDEBUG}
  1153. DebugLogger('Domain ' + domain +
  1154. ': File does not exist, neither embedded or in file system: ' +
  1155. filename);
  1156. {$ENDIF}
  1157. filename := Directory + MidStr(curlang, 1, 2) + PathDelim +
  1158. 'LC_MESSAGES' + PathDelim + domain + '.mo';
  1159. {$IFDEF DXGETTEXTDEBUG}
  1160. DebugLogger('Domain ' + domain + ' will attempt to use this file: '
  1161. + filename);
  1162. {$ENDIF}
  1163. end
  1164. else
  1165. begin
  1166. {$IFDEF DXGETTEXTDEBUG}
  1167. if FileLocator.FileExists(filename) then
  1168. DebugLogger('Domain ' + domain +
  1169. ' will attempt to use this embedded file: ' + filename)
  1170. else
  1171. DebugLogger('Domain ' + domain +
  1172. ' will attempt to use this file that was found on the file system: '
  1173. + filename);
  1174. {$ENDIF}
  1175. end;
  1176. end;
  1177. if (not FileLocator.FileExists(filename)) and (not FileExists(filename))
  1178. then
  1179. begin
  1180. {$IFDEF DXGETTEXTDEBUG}
  1181. DebugLogger('Domain ' + domain + ' failed to locate the file: ' +
  1182. filename);
  1183. {$ENDIF}
  1184. OpenHasFailedBefore := True;
  1185. exit;
  1186. end;
  1187. {$IFDEF DXGETTEXTDEBUG}
  1188. DebugLogger('Domain ' + domain + ' now accesses the file.');
  1189. {$ENDIF}
  1190. mofile := FileLocator.GetMoFile(filename, DebugLogger);
  1191. {$IFDEF DXGETTEXTDEBUG}
  1192. if mofile.isSwappedArchitecture then
  1193. DebugLogger
  1194. ('.mo file is swapped (comes from another CPU architecture)');
  1195. {$ENDIF}
  1196. // Check, that the contents of the file is utf-8
  1197. if pos('CHARSET=UTF-8',
  1198. uppercase(GetTranslationProperty('Content-Type'))) = 0 then
  1199. begin
  1200. CloseMoFile;
  1201. {$IFDEF DXGETTEXTDEBUG}
  1202. DebugLogger('The translation for the language code ' + curlang +
  1203. ' (in ' + filename +
  1204. ') does not have charset=utf-8 in its Content-Type. Translations are turned off.');
  1205. {$ENDIF}
  1206. {$IFDEF MSWINDOWS}
  1207. MessageBoxW(0,
  1208. PWideChar(WideString('The translation for the language code ' +
  1209. curlang + ' (in ' + filename +
  1210. ') does not have charset=utf-8 in its Content-Type. Translations are turned off.')
  1211. ), 'Localization problem', MB_OK);
  1212. {$ELSE}
  1213. writeln(stderr, 'The translation for the language code ' + curlang +
  1214. ' (in ' + filename +
  1215. ') does not have charset=utf-8 in its Content-Type. Translations are turned off.');
  1216. {$ENDIF}
  1217. enabled := false;
  1218. end;
  1219. end;
  1220. {$IFDEF UNICODE}
  1221. function utf8decode(s: RawByteString): UnicodeString; inline;
  1222. begin
  1223. Result := UTF8ToWideString(s);
  1224. end;
  1225. {$ENDIF}
  1226. function TDomain.GetTranslationProperty(propertyname: ComponentNameString)
  1227. : TranslatedUnicodeString;
  1228. var
  1229. sl: TStringList;
  1230. i: Integer;
  1231. s: string;
  1232. begin
  1233. propertyname := uppercase(propertyname) + ': ';
  1234. sl := TStringList.Create;
  1235. try
  1236. sl.Text := utf8decode(gettext(''));
  1237. for i := 0 to sl.Count - 1 do
  1238. begin
  1239. s := sl.Strings[i];
  1240. if uppercase(MidStr(s, 1, length(propertyname))) = propertyname then
  1241. begin
  1242. Result := trim(MidStr(s, length(propertyname) + 1, maxint));
  1243. {$IFDEF DXGETTEXTDEBUG}
  1244. DebugLogger('GetTranslationProperty(' + propertyname +
  1245. ') returns ''' + Result + '''.');
  1246. {$ENDIF}
  1247. exit;
  1248. end;
  1249. end;
  1250. finally
  1251. FreeAndNil(sl);
  1252. end;
  1253. Result := '';
  1254. {$IFDEF DXGETTEXTDEBUG}
  1255. DebugLogger('GetTranslationProperty(' + propertyname +
  1256. ') did not find any value. An empty string is returned.');
  1257. {$ENDIF}
  1258. end;
  1259. procedure TDomain.setDirectory(const dir: FilenameString);
  1260. begin
  1261. vDirectory := IncludeTrailingPathDelimiter(dir);
  1262. SpecificFilename := '';
  1263. CloseMoFile;
  1264. end;
  1265. procedure AddDomainForResourceString(const domain: DomainString);
  1266. begin
  1267. {$IFDEF DXGETTEXTDEBUG}
  1268. DefaultInstance.DebugWriteln('Extra domain for resourcestring: '
  1269. + domain);
  1270. {$ENDIF}
  1271. ResourceStringDomainListCS.BeginWrite;
  1272. try
  1273. if ResourceStringDomainList.IndexOf(domain) = -1 then
  1274. ResourceStringDomainList.Add(domain);
  1275. finally
  1276. ResourceStringDomainListCS.EndWrite;
  1277. end;
  1278. end;
  1279. procedure RemoveDomainForResourceString(const domain: DomainString);
  1280. var
  1281. i: Integer;
  1282. begin
  1283. {$IFDEF DXGETTEXTDEBUG}
  1284. DefaultInstance.DebugWriteln('Remove domain for resourcestring: '
  1285. + domain);
  1286. {$ENDIF}
  1287. ResourceStringDomainListCS.BeginWrite;
  1288. try
  1289. i := ResourceStringDomainList.IndexOf(domain);
  1290. if i <> -1 then
  1291. ResourceStringDomainList.delete(i);
  1292. finally
  1293. ResourceStringDomainListCS.EndWrite;
  1294. end;
  1295. end;
  1296. procedure AddDomains(const Domains: array of DomainString);
  1297. var
  1298. i: Integer;
  1299. begin
  1300. for i := 0 to High(Domains) do
  1301. AddDomainForResourceString(Domains[i]);
  1302. end;
  1303. procedure AddDomainForComponent(const domain: DomainString);
  1304. begin
  1305. {$IFDEF DXGETTEXTDEBUG}
  1306. DefaultInstance.DebugWriteln('Extra domain for component: ' + domain);
  1307. {$ENDIF}
  1308. ComponentDomainListCS.BeginWrite;
  1309. try
  1310. if ComponentDomainList.IndexOf(domain) = -1 then
  1311. ComponentDomainList.Add(domain);
  1312. finally
  1313. ComponentDomainListCS.EndWrite;
  1314. end;
  1315. end;
  1316. procedure RemoveDomainForComponent(const domain: DomainString);
  1317. var
  1318. i: Integer;
  1319. begin
  1320. {$IFDEF DXGETTEXTDEBUG}
  1321. DefaultInstance.DebugWriteln('Remove domain for component: ' + domain);
  1322. {$ENDIF}
  1323. ComponentDomainListCS.BeginWrite;
  1324. try
  1325. i := ComponentDomainList.IndexOf(domain);
  1326. if i <> -1 then
  1327. ComponentDomainList.delete(i);
  1328. finally
  1329. ComponentDomainListCS.EndWrite;
  1330. end;
  1331. end;
  1332. procedure TDomain.SetLanguageCode(const langcode: LanguageString);
  1333. begin
  1334. CloseMoFile;
  1335. curlang := langcode;
  1336. end;
  1337. function GetPluralForm2EN(Number: Integer): Integer;
  1338. begin
  1339. Number := abs(Number);
  1340. if Number = 1 then
  1341. Result := 0
  1342. else
  1343. Result := 1;
  1344. end;
  1345. function GetPluralForm1(Number: Integer): Integer;
  1346. begin
  1347. Result := 0;
  1348. end;
  1349. function GetPluralForm2FR(Number: Integer): Integer;
  1350. begin
  1351. Number := abs(Number);
  1352. if (Number = 1) or (Number = 0) then
  1353. Result := 0
  1354. else
  1355. Result := 1;
  1356. end;
  1357. function GetPluralForm3LV(Number: Integer): Integer;
  1358. begin
  1359. Number := abs(Number);
  1360. if (Number mod 10 = 1) and (Number mod 100 <> 11) then
  1361. Result := 0
  1362. else if Number <> 0 then
  1363. Result := 1
  1364. else
  1365. Result := 2;
  1366. end;
  1367. function GetPluralForm3GA(Number: Integer): Integer;
  1368. begin
  1369. Number := abs(Number);
  1370. if Number = 1 then
  1371. Result := 0
  1372. else if Number = 2 then
  1373. Result := 1
  1374. else
  1375. Result := 2;
  1376. end;
  1377. function GetPluralForm3LT(Number: Integer): Integer;
  1378. var
  1379. n1, n2: byte;
  1380. begin
  1381. Number := abs(Number);
  1382. n1 := Number mod 10;
  1383. n2 := Number mod 100;
  1384. if (n1 = 1) and (n2 <> 11) then
  1385. Result := 0
  1386. else if (n1 >= 2) and ((n2 < 10) or (n2 >= 20)) then
  1387. Result := 1
  1388. else
  1389. Result := 2;
  1390. end;
  1391. function GetPluralForm3PL(Number: Integer): Integer;
  1392. var
  1393. n1, n2: byte;
  1394. begin
  1395. Number := abs(Number);
  1396. n1 := Number mod 10;
  1397. n2 := Number mod 100;
  1398. if Number = 1 then
  1399. Result := 0
  1400. else if (n1 >= 2) and (n1 <= 4) and ((n2 < 10) or (n2 >= 20)) then
  1401. Result := 1
  1402. else
  1403. Result := 2;
  1404. end;
  1405. function GetPluralForm3RU(Number: Integer): Integer;
  1406. var
  1407. n1, n2: byte;
  1408. begin
  1409. Number := abs(Number);
  1410. n1 := Number mod 10;
  1411. n2 := Number mod 100;
  1412. if (n1 = 1) and (n2 <> 11) then
  1413. Result := 0
  1414. else if (n1 >= 2) and (n1 <= 4) and ((n2 < 10) or (n2 >= 20)) then
  1415. Result := 1
  1416. else
  1417. Result := 2;
  1418. end;
  1419. function GetPluralForm3SK(Number: Integer): Integer;
  1420. begin
  1421. Number := abs(Number);
  1422. if Number = 1 then
  1423. Result := 0
  1424. else if (Number < 5) and (Number <> 0) then
  1425. Result := 1
  1426. else
  1427. Result := 2;
  1428. end;
  1429. function GetPluralForm4SL(Number: Integer): Integer;
  1430. var
  1431. n2: byte;
  1432. begin
  1433. Number := abs(Number);
  1434. n2 := Number mod 100;
  1435. if n2 = 1 then
  1436. Result := 0
  1437. else if n2 = 2 then
  1438. Result := 1
  1439. else if (n2 = 3) or (n2 = 4) then
  1440. Result := 2
  1441. else
  1442. Result := 3;
  1443. end;
  1444. procedure TDomain.GetListOfLanguages(list: TStrings);
  1445. var
  1446. sr: TSearchRec;
  1447. more: boolean;
  1448. filename, path: FilenameString;
  1449. langcode: LanguageString;
  1450. i, j: Integer;
  1451. begin
  1452. list.Clear;
  1453. // Iterate through filesystem
  1454. more := FindFirst(Directory + '*', faAnyFile, sr) = 0;
  1455. try
  1456. while more do
  1457. begin
  1458. if (sr.Attr and faDirectory <> 0) and (sr.name <> '.') and
  1459. (sr.name <> '..') then
  1460. begin
  1461. filename := Directory + sr.name + PathDelim + 'LC_MESSAGES' +
  1462. PathDelim + domain + '.mo';
  1463. if FileExists(filename) then
  1464. begin
  1465. langcode := lowercase(sr.name);
  1466. if list.IndexOf(langcode) = -1 then
  1467. list.Add(langcode);
  1468. end;
  1469. end;
  1470. more := FindNext(sr) = 0;
  1471. end;
  1472. finally
  1473. FindClose(sr);
  1474. end;
  1475. // Iterate through embedded files
  1476. for i := 0 to FileLocator.filelist.Count - 1 do
  1477. begin
  1478. filename := FileLocator.basedirectory +
  1479. FileLocator.filelist.Strings[i];
  1480. path := Directory;
  1481. {$IFDEF MSWINDOWS}
  1482. path := uppercase(path);
  1483. filename := uppercase(filename);
  1484. {$ENDIF}
  1485. j := length(path);
  1486. if MidStr(filename, 1, j) = path then
  1487. begin
  1488. path := PathDelim + 'LC_MESSAGES' + PathDelim + domain + '.mo';
  1489. {$IFDEF MSWINDOWS}
  1490. path := uppercase(path);
  1491. {$ENDIF}
  1492. if MidStr(filename, length(filename) - length(path) + 1,
  1493. length(path)) = path then
  1494. begin
  1495. langcode :=
  1496. lowercase(MidStr(filename, j + 1,
  1497. length(filename) - length(path) - j));
  1498. langcode := LeftStr(langcode, 3) +
  1499. uppercase(MidStr(langcode, 4, maxint));
  1500. if list.IndexOf(langcode) = -1 then
  1501. list.Add(langcode);
  1502. end;
  1503. end;
  1504. end;
  1505. end;
  1506. procedure TDomain.SetFilename(const filename: FilenameString);
  1507. begin
  1508. CloseMoFile;
  1509. vDirectory := '';
  1510. SpecificFilename := filename;
  1511. end;
  1512. function TDomain.gettext(const msgid: RawUtf8String): RawUtf8String;
  1513. var
  1514. found: boolean;
  1515. begin
  1516. if not enabled then
  1517. begin
  1518. Result := msgid;
  1519. exit;
  1520. end;
  1521. if (mofile = nil) and (not OpenHasFailedBefore) then
  1522. OpenMoFile;
  1523. if mofile = nil then
  1524. begin
  1525. {$IFDEF DXGETTEXTDEBUG}
  1526. DebugLogger('.mo file is not open. Not translating "' + msgid + '"');
  1527. {$ENDIF}
  1528. Result := msgid;
  1529. end
  1530. else
  1531. begin
  1532. Result := mofile.gettext(msgid, found);
  1533. {$IFDEF DXGETTEXTDEBUG}
  1534. if found then
  1535. DebugLogger('Found in .mo (' + domain + '): "' + utf8encode(msgid) +
  1536. '"->"' + utf8encode(Result) + '"')
  1537. else
  1538. DebugLogger('Translation not found in .mo file (' + domain + ') : "'
  1539. + utf8encode(msgid) + '"');
  1540. {$ENDIF}
  1541. end;
  1542. end;
  1543. constructor TDomain.Create;
  1544. begin
  1545. inherited Create;
  1546. enabled := True;
  1547. end;
  1548. { TGnuGettextInstance }
  1549. procedure TGnuGettextInstance.bindtextdomain(const szDomain: DomainString;
  1550. const szDirectory: FilenameString);
  1551. var
  1552. dir: FilenameString;
  1553. begin
  1554. dir := IncludeTrailingPathDelimiter(szDirectory);
  1555. {$IFDEF DXGETTEXTDEBUG}
  1556. DebugWriteln('Text domain "' + szDomain + '" is now located at "' +
  1557. dir + '"');
  1558. {$ENDIF}
  1559. Getdomain(szDomain, DefaultDomainDirectory, curlang).Directory := dir;
  1560. WhenNewDomainDirectory(szDomain, szDirectory);
  1561. end;
  1562. constructor TGnuGettextInstance.Create;
  1563. begin
  1564. {$IFDEF MSWindows}
  1565. DesignTimeCodePage := CP_ACP;
  1566. {$ENDIF}
  1567. {$IFDEF DXGETTEXTDEBUG}
  1568. DebugLogCS := TMultiReadExclusiveWriteSynchronizer.Create;
  1569. DebugLog := TMemoryStream.Create;
  1570. DebugWriteln('Debug log started ' + DateTimeToStr(Now));
  1571. DebugWriteln('GNU gettext module version: ' + VCSVersion);
  1572. DebugWriteln('');
  1573. {$ENDIF}
  1574. curGetPluralForm := GetPluralForm2EN;
  1575. enabled := True;
  1576. curmsgdomain := DefaultTextDomain;
  1577. savefileCS := TMultiReadExclusiveWriteSynchronizer.Create;
  1578. domainlist := TStringList.Create;
  1579. TP_IgnoreList := TStringList.Create;
  1580. TP_IgnoreList.Sorted := True;
  1581. TP_GlobalClassHandling := TList.Create;
  1582. TP_ClassHandling := TList.Create;
  1583. fWhenNewLanguageListeners := TInterfaceList.Create;
  1584. // Set some settings
  1585. DefaultDomainDirectory := IncludeTrailingPathDelimiter
  1586. (extractfilepath(ExecutableFilename)) + 'locale';
  1587. UseLanguage('');
  1588. bindtextdomain(DefaultTextDomain, DefaultDomainDirectory);
  1589. textdomain(DefaultTextDomain);
  1590. // Add default properties to ignore
  1591. TP_GlobalIgnoreClassProperty(TComponent, 'Name');
  1592. TP_GlobalIgnoreClassProperty(TCollection, 'PropName');
  1593. end;
  1594. destructor TGnuGettextInstance.Destroy;
  1595. begin
  1596. if savememory <> nil then
  1597. begin
  1598. savefileCS.BeginWrite;
  1599. try
  1600. CloseFile(savefile);
  1601. finally
  1602. savefileCS.EndWrite;
  1603. end;
  1604. FreeAndNil(savememory);
  1605. end;
  1606. FreeAndNil(savefileCS);
  1607. FreeAndNil(TP_IgnoreList);
  1608. while TP_GlobalClassHandling.Count <> 0 do
  1609. begin
  1610. TObject(TP_GlobalClassHandling.Items[0]).Free;
  1611. TP_GlobalClassHandling.delete(0);
  1612. end;
  1613. FreeAndNil(TP_GlobalClassHandling);
  1614. FreeTP_ClassHandlingItems;
  1615. FreeAndNil(TP_ClassHandling);
  1616. while domainlist.Count <> 0 do
  1617. begin
  1618. domainlist.Objects[0].Free;
  1619. domainlist.delete(0);
  1620. end;
  1621. FreeAndNil(domainlist);
  1622. fWhenNewLanguageListeners.Free;
  1623. {$IFDEF DXGETTEXTDEBUG}
  1624. FreeAndNil(DebugLog);
  1625. FreeAndNil(DebugLogCS);
  1626. {$ENDIF}
  1627. inherited;
  1628. end;
  1629. {$IFNDEF UNICODE}
  1630. function TGnuGettextInstance.dgettext(const szDomain: DomainString;
  1631. const szMsgId: AnsiString): TranslatedUnicodeString;
  1632. begin
  1633. Result := dgettext(szDomain, ansi2wideDTCP(szMsgId));
  1634. end;
  1635. {$ENDIF}
  1636. function TGnuGettextInstance.dgettext(const szDomain: DomainString;
  1637. const szMsgId: MsgIdString): TranslatedUnicodeString;
  1638. begin
  1639. if not enabled then
  1640. begin
  1641. {$IFDEF DXGETTEXTDEBUG}
  1642. DebugWriteln
  1643. ('Translation has been disabled. Text is not being translated: '
  1644. + szMsgId);
  1645. {$ENDIF}
  1646. Result := szMsgId;
  1647. end
  1648. else
  1649. begin
  1650. Result := utf8decode(EnsureLineBreakInTranslatedString
  1651. (Getdomain(szDomain, DefaultDomainDirectory, curlang)
  1652. .gettext(StripCRRawMsgId(utf8encode(szMsgId)))));
  1653. {$IFDEF DXGETTEXTDEBUG}
  1654. if (szMsgId <> '') and (Result = '') then
  1655. DebugWriteln
  1656. (Format('Error: Translation of %s was an empty string. This may never occur.',
  1657. [szMsgId]));
  1658. {$ENDIF}
  1659. end;
  1660. end;
  1661. function TGnuGettextInstance.dgettext_NoExtract(const szDomain
  1662. : DomainString; const szMsgId: MsgIdString): TranslatedUnicodeString;
  1663. begin
  1664. // This one is very useful for translating text in variables.
  1665. // This can sometimes be necessary, and by using this function,
  1666. // the source code scanner will not trigger warnings.
  1667. Result := dgettext(szDomain, szMsgId);
  1668. end;
  1669. function TGnuGettextInstance.GetCurrentLanguage: LanguageString;
  1670. begin
  1671. Result := curlang;
  1672. end;
  1673. function TGnuGettextInstance.getcurrenttextdomain: DomainString;
  1674. begin
  1675. Result := curmsgdomain;
  1676. end;
  1677. {$IFNDEF UNICODE}
  1678. function TGnuGettextInstance.gettext(const szMsgId: AnsiString)
  1679. : TranslatedUnicodeString;
  1680. begin
  1681. Result := dgettext(curmsgdomain, szMsgId);
  1682. end;
  1683. {$ENDIF}
  1684. function TGnuGettextInstance.gettext(const szMsgId: MsgIdString)
  1685. : TranslatedUnicodeString;
  1686. begin
  1687. Result := dgettext(curmsgdomain, szMsgId);
  1688. end;
  1689. function TGnuGettextInstance.gettext_NoExtract(const szMsgId: MsgIdString)
  1690. : TranslatedUnicodeString;
  1691. begin
  1692. // This one is very useful for translating text in variables.
  1693. // This can sometimes be necessary, and by using this function,
  1694. // the source code scanner will not trigger warnings.
  1695. Result := gettext(szMsgId);
  1696. end;
  1697. function TGnuGettextInstance.gettext_NoOp(const szMsgId: MsgIdString)
  1698. : TranslatedUnicodeString;
  1699. begin
  1700. // *** With this function Strings can be added to the po-file without beeing
  1701. // ResourceStrings (dxgettext will add the string and this function will
  1702. // return it without a change)
  1703. // see gettext manual
  1704. // 4.7 - Special Cases of Translatable Strings
  1705. // http://www.gnu.org/software/hello/manual/gettext/Special-cases.html#Special-cases
  1706. Result := TranslatedUnicodeString(szMsgId);
  1707. end;
  1708. procedure TGnuGettextInstance.textdomain(const szDomain: DomainString);
  1709. begin
  1710. {$IFDEF DXGETTEXTDEBUG}
  1711. DebugWriteln('Changed text domain to "' + szDomain + '"');
  1712. {$ENDIF}
  1713. curmsgdomain := szDomain;
  1714. WhenNewDomain(szDomain);
  1715. end;
  1716. function TGnuGettextInstance.TP_CreateRetranslator: TExecutable;
  1717. var
  1718. ttpr: TTP_Retranslator;
  1719. begin
  1720. ttpr := TTP_Retranslator.Create;
  1721. ttpr.Instance := self;
  1722. TP_Retranslator := ttpr;
  1723. Result := ttpr;
  1724. {$IFDEF DXGETTEXTDEBUG}
  1725. DebugWriteln('A retranslator was created.');
  1726. {$ENDIF}
  1727. end;
  1728. procedure TGnuGettextInstance.TP_GlobalHandleClass(HClass: TClass;
  1729. Handler: TTranslator);
  1730. var
  1731. cm: TClassMode;
  1732. i: Integer;
  1733. begin
  1734. for i := 0 to TP_GlobalClassHandling.Count - 1 do
  1735. begin
  1736. cm := TObject(TP_GlobalClassHandling.Items[i]) as TClassMode;
  1737. if cm.HClass = HClass then
  1738. raise EGGProgrammingError.Create
  1739. ('You cannot set a handler for a class that has already been assigned otherwise.');
  1740. if HClass.InheritsFrom(cm.HClass) then
  1741. begin
  1742. // This is the place to insert this class
  1743. cm := TClassMode.Create;
  1744. cm.HClass := HClass;
  1745. cm.SpecialHandler := Handler;
  1746. TP_GlobalClassHandling.insert(i, cm);
  1747. {$IFDEF DXGETTEXTDEBUG}
  1748. DebugWriteln('A handler was set for class ' +
  1749. HClass.ClassName + '.');
  1750. {$ENDIF}
  1751. exit;
  1752. end;
  1753. end;
  1754. cm := TClassMode.Create;
  1755. cm.HClass := HClass;
  1756. cm.SpecialHandler := Handler;
  1757. TP_GlobalClassHandling.Add(cm);
  1758. {$IFDEF DXGETTEXTDEBUG}
  1759. DebugWriteln('A handler was set for class ' + HClass.ClassName + '.');
  1760. {$ENDIF}
  1761. end;
  1762. procedure TGnuGettextInstance.TP_GlobalIgnoreClass(IgnClass: TClass);
  1763. var
  1764. cm: TClassMode;
  1765. i: Integer;
  1766. begin
  1767. for i := 0 to TP_GlobalClassHandling.Count - 1 do
  1768. begin
  1769. cm := TObject(TP_GlobalClassHandling.Items[i]) as TClassMode;
  1770. if cm.HClass = IgnClass then
  1771. raise EGGProgrammingError.Create
  1772. ('You cannot add a class to the ignore list that is already on that list: '
  1773. + IgnClass.ClassName +
  1774. '. You should keep all TP_Global functions in one place in your source code.');
  1775. if IgnClass.InheritsFrom(cm.HClass) then
  1776. begin
  1777. // This is the place to insert this class
  1778. cm := TClassMode.Create;
  1779. cm.HClass := IgnClass;
  1780. TP_GlobalClassHandling.insert(i, cm);
  1781. {$IFDEF DXGETTEXTDEBUG}
  1782. DebugWriteln('Globally, class ' + IgnClass.ClassName +
  1783. ' is being ignored.');
  1784. {$ENDIF}
  1785. exit;
  1786. end;
  1787. end;
  1788. cm := TClassMode.Create;
  1789. cm.HClass := IgnClass;
  1790. TP_GlobalClassHandling.Add(cm);
  1791. {$IFDEF DXGETTEXTDEBUG}
  1792. DebugWriteln('Globally, class ' + IgnClass.ClassName +
  1793. ' is being ignored.');
  1794. {$ENDIF}
  1795. end;
  1796. procedure TGnuGettextInstance.TP_GlobalIgnoreClassProperty
  1797. (IgnClass: TClass; propertyname: ComponentNameString);
  1798. var
  1799. cm: TClassMode;
  1800. i, idx: Integer;
  1801. begin
  1802. propertyname := uppercase(propertyname);
  1803. for i := 0 to TP_GlobalClassHandling.Count - 1 do
  1804. begin
  1805. cm := TObject(TP_GlobalClassHandling.Items[i]) as TClassMode;
  1806. if cm.HClass = IgnClass then
  1807. begin
  1808. if Assigned(cm.SpecialHandler) then
  1809. raise EGGProgrammingError.Create
  1810. ('You cannot ignore a class property for a class that has a handler set.');
  1811. if not cm.PropertiesToIgnore.Find(propertyname, idx) then
  1812. cm.PropertiesToIgnore.Add(propertyname);
  1813. {$IFDEF DXGETTEXTDEBUG}
  1814. DebugWriteln('Globally, the ' + propertyname + ' property of class '
  1815. + IgnClass.ClassName + ' is being ignored.');
  1816. {$ENDIF}
  1817. exit;
  1818. end;
  1819. if IgnClass.InheritsFrom(cm.HClass) then
  1820. begin
  1821. // This is the place to insert this class
  1822. cm := TClassMode.Create;
  1823. cm.HClass := IgnClass;
  1824. cm.PropertiesToIgnore.Add(propertyname);
  1825. TP_GlobalClassHandling.insert(i, cm);
  1826. {$IFDEF DXGETTEXTDEBUG}
  1827. DebugWriteln('Globally, the ' + propertyname + ' property of class '
  1828. + IgnClass.ClassName + ' is being ignored.');
  1829. {$ENDIF}
  1830. exit;
  1831. end;
  1832. end;
  1833. cm := TClassMode.Create;
  1834. cm.HClass := IgnClass;
  1835. cm.PropertiesToIgnore.Add(propertyname);
  1836. TP_GlobalClassHandling.Add(cm);
  1837. {$IFDEF DXGETTEXTDEBUG}
  1838. DebugWriteln('Globally, the ' + propertyname + ' property of class ' +
  1839. IgnClass.ClassName + ' is being ignored.');
  1840. {$ENDIF}
  1841. end;
  1842. procedure TGnuGettextInstance.TP_Ignore(AnObject: TObject;
  1843. const name: ComponentNameString);
  1844. begin
  1845. TP_IgnoreList.Add(uppercase(name));
  1846. {$IFDEF DXGETTEXTDEBUG}
  1847. DebugWriteln('On object with class name ' + AnObject.ClassName +
  1848. ', ignore is set on ' + name);
  1849. {$ENDIF}
  1850. end;
  1851. procedure TGnuGettextInstance.TranslateComponent(AnObject: TComponent;
  1852. const textdomain: DomainString);
  1853. var
  1854. comp: TGnuGettextComponentMarker;
  1855. begin
  1856. {$IFDEF DXGETTEXTDEBUG}
  1857. DebugWriteln
  1858. ('======================================================================');
  1859. DebugWriteln
  1860. ('TranslateComponent() was called for a component with name ' +
  1861. AnObject.name + '.');
  1862. {$ENDIF}
  1863. comp := AnObject.FindComponent('GNUgettextMarker')
  1864. as TGnuGettextComponentMarker;
  1865. if comp = nil then
  1866. begin
  1867. comp := TGnuGettextComponentMarker.Create(nil);
  1868. comp.name := 'GNUgettextMarker';
  1869. comp.Retranslator := TP_CreateRetranslator;
  1870. TranslateProperties(AnObject, textdomain);
  1871. AnObject.InsertComponent(comp);
  1872. {$IFDEF DXGETTEXTDEBUG}
  1873. DebugWriteln
  1874. ('This is the first time, that this component has been translated. A retranslator component has been created for this component.');
  1875. {$ENDIF}
  1876. end
  1877. else
  1878. begin
  1879. {$IFDEF DXGETTEXTDEBUG}
  1880. DebugWriteln
  1881. ('This is not the first time, that this component has been translated.');
  1882. {$ENDIF}
  1883. if comp.LastLanguage <> curlang then
  1884. begin
  1885. {$IFDEF DXGETTEXTDEBUG}
  1886. DebugWriteln
  1887. ('ERROR: TranslateComponent() was called twice with different languages. This indicates an attempt to switch language at runtime, but by using TranslateComponent every time. This API has changed - please use RetranslateComponent() instead.');
  1888. {$ENDIF}
  1889. {$IFDEF mswindows}
  1890. MessageBox(0,
  1891. 'This application tried to switch the language, but in an incorrect way. The programmer needs to replace a call to TranslateComponent with a call to RetranslateComponent(). The programmer should see the changelog of gnugettext.pas for more information.',
  1892. 'Error', MB_OK);
  1893. {$ELSE}
  1894. writeln(stderr,
  1895. 'This application tried to switch the language, but in an incorrect way. The programmer needs to replace a call to TranslateComponent with a call to RetranslateComponent(). The programmer should see the changelog of gnugettext.pas for more information.');
  1896. {$ENDIF}
  1897. end
  1898. else
  1899. begin
  1900. {$IFDEF DXGETTEXTDEBUG}
  1901. DebugWriteln
  1902. ('ERROR: TranslateComponent has been called twice, but with the same language chosen. This is a mistake, but in order to prevent that the application breaks, no exception is raised.');
  1903. {$ENDIF}
  1904. end;
  1905. end;
  1906. comp.LastLanguage := curlang;
  1907. {$IFDEF DXGETTEXTDEBUG}
  1908. DebugWriteln
  1909. ('======================================================================');
  1910. {$ENDIF}
  1911. end;
  1912. procedure TGnuGettextInstance.TranslateProperty(AnObject: TObject;
  1913. PropInfo: PPropInfo; TodoList: TStrings;
  1914. const textdomain: DomainString);
  1915. var
  1916. ppi: PPropInfo;
  1917. ws: TranslatedUnicodeString;
  1918. old: TranslatedUnicodeString;
  1919. compmarker: TComponent;
  1920. obj: TObject;
  1921. Propname: ComponentNameString;
  1922. begin
  1923. Propname := string(PropInfo^.name);
  1924. try
  1925. // Translate certain types of properties
  1926. case PropInfo^.PropType^.Kind of
  1927. {$IFDEF UNICODE}
  1928. // All dfm files returning tkUString
  1929. tkString, tkLString, tkWString, tkUString:
  1930. {$ELSE}
  1931. tkString, tkLString, tkWString:
  1932. {$ENDIF}
  1933. begin
  1934. // prevent items in RadioGroup from duplicate translation - JR - 2011-07-29
  1935. if AnObject.ClassName = 'TGroupButton' then
  1936. exit;
  1937. {$IFDEF DXGETTEXTDEBUG}
  1938. if AnObject is TComponent then
  1939. DebugWriteln('Translating ' + AnObject.ClassName + '.' +
  1940. Propname + ' (' + TComponent(AnObject).name + ')')
  1941. else
  1942. DebugWriteln('Translating ' + AnObject.ClassName + '.' +
  1943. Propname);;
  1944. {$ENDIF}
  1945. case PropInfo^.PropType^.Kind of
  1946. tkString, tkLString:
  1947. old := GetStrProp(AnObject, Propname);
  1948. tkWString:
  1949. old := GetWideStrProp(AnObject, Propname);
  1950. {$IFDEF UNICODE}
  1951. tkUString:
  1952. old := GetUnicodeStrProp(AnObject, Propname);
  1953. {$ENDIF}
  1954. else
  1955. raise Exception.Create
  1956. ('Internal error: Illegal property type. This problem needs to be solved by a programmer, try to find a workaround.');
  1957. end;
  1958. {$IFDEF DXGETTEXTDEBUG}
  1959. if old = '' then
  1960. DebugWriteln('(Empty, not translated)')
  1961. else
  1962. DebugWriteln('Old value: "' + old + '"');
  1963. {$ENDIF}
  1964. if (old <> '') and (IsWriteProp(PropInfo)) then
  1965. begin
  1966. if TP_Retranslator <> nil then
  1967. (TP_Retranslator as TTP_Retranslator)
  1968. .Remember(AnObject, Propname, old);
  1969. if textdomain = '' then
  1970. ws := ComponentGettext(old)
  1971. else
  1972. ws := dgettext(textdomain, old);
  1973. if ws <> old then
  1974. begin
  1975. ppi := GetPropInfo(AnObject, Propname);
  1976. if ppi <> nil then
  1977. begin
  1978. SetWideStrProp(AnObject, ppi, ws);
  1979. end
  1980. else
  1981. begin
  1982. {$IFDEF DXGETTEXTDEBUG}
  1983. DebugWriteln('ERROR: Property disappeared: ' + Propname +
  1984. ' for object of type ' + AnObject.ClassName);
  1985. {$ENDIF}
  1986. end;
  1987. end;
  1988. end;
  1989. end { case item };
  1990. tkClass:
  1991. begin
  1992. obj := GetObjectProp(AnObject, Propname);
  1993. if obj <> nil then
  1994. begin
  1995. if obj is TComponent then
  1996. begin
  1997. compmarker := TComponent(obj)
  1998. .FindComponent('GNUgettextMarker');
  1999. if Assigned(compmarker) then
  2000. exit;
  2001. end;
  2002. TodoList.AddObject('', obj);
  2003. end;
  2004. end { case item };
  2005. end { case };
  2006. except
  2007. on E: Exception do
  2008. raise EGGComponentError.Create('Property cannot be translated.' +
  2009. sLinebreak + 'Add TP_GlobalIgnoreClassProperty(' +
  2010. AnObject.ClassName + ',''' + Propname +
  2011. ''') to your source code or use' + sLinebreak +
  2012. 'TP_Ignore (self,''.' + Propname + ''') to prevent this message.'
  2013. + sLinebreak + 'Reason: ' + E.Message);
  2014. end;
  2015. end;
  2016. procedure TGnuGettextInstance.TranslateProperties(AnObject: TObject;
  2017. textdomain: DomainString = '');
  2018. var
  2019. TodoList: TStringList; // List of Name/TObject's that is to be processed
  2020. DoneList: TStringList;
  2021. // List of hex codes representing pointers to objects that have been done
  2022. i, j, Count: Integer;
  2023. PropList: PPropList;
  2024. UPropName: ComponentNameString;
  2025. PropInfo: PPropInfo;
  2026. compmarker, comp: TComponent;
  2027. cm, currentcm: TClassMode;
  2028. // currentcm is nil or contains special information about how to handle the current object
  2029. ObjectPropertyIgnoreList: TStringList;
  2030. objid: string;
  2031. name: ComponentNameString;
  2032. begin
  2033. {$IFDEF DXGETTEXTDEBUG}
  2034. DebugWriteln
  2035. ('----------------------------------------------------------------------');
  2036. DebugWriteln('TranslateProperties() was called for an object of class '
  2037. + AnObject.ClassName + ' with domain "' + textdomain + '".');
  2038. {$ENDIF}
  2039. if TP_Retranslator <> nil then
  2040. if textdomain = '' then
  2041. (TP_Retranslator as TTP_Retranslator).textdomain := curmsgdomain
  2042. else
  2043. (TP_Retranslator as TTP_Retranslator).textdomain := textdomain;
  2044. {$IFDEF FPC}
  2045. DoneList := TCSStringList.Create;
  2046. TodoList := TCSStringList.Create;
  2047. ObjectPropertyIgnoreList := TCSStringList.Create;
  2048. {$ELSE}
  2049. DoneList := TStringList.Create;
  2050. TodoList := TStringList.Create;
  2051. ObjectPropertyIgnoreList := TStringList.Create;
  2052. {$ENDIF}
  2053. try
  2054. TodoList.AddObject('', AnObject);
  2055. DoneList.Sorted := True;
  2056. ObjectPropertyIgnoreList.Sorted := True;
  2057. ObjectPropertyIgnoreList.Duplicates := dupIgnore;
  2058. ObjectPropertyIgnoreList.CaseSensitive := false;
  2059. DoneList.Duplicates := dupError;
  2060. DoneList.CaseSensitive := True;
  2061. while TodoList.Count <> 0 do
  2062. begin
  2063. AnObject := TodoList.Objects[0];
  2064. Name := TodoList.Strings[0];
  2065. TodoList.delete(0);
  2066. if (AnObject <> nil) and (AnObject is TPersistent) then
  2067. begin
  2068. // Make sure each object is only translated once
  2069. Assert(SizeOf({$IFDEF CPUx64}NativeInt{$ELSE}Integer{$ENDIF CPUx64}) = SizeOf(TObject));
  2070. objid := IntToHex
  2071. ({$IFDEF CPUx64}NativeInt{$ELSE}Integer{$ENDIF CPUx64}(AnObject), 8);
  2072. if DoneList.Find(objid, i) then
  2073. begin
  2074. continue;
  2075. end
  2076. else
  2077. begin
  2078. DoneList.Add(objid);
  2079. end;
  2080. ObjectPropertyIgnoreList.Clear;
  2081. // Find out if there is special handling of this object
  2082. currentcm := nil;
  2083. // First check the local handling instructions
  2084. for j := 0 to TP_ClassHandling.Count - 1 do
  2085. begin
  2086. cm := TObject(TP_ClassHandling.Items[j]) as TClassMode;
  2087. if AnObject.InheritsFrom(cm.HClass) then
  2088. begin
  2089. if cm.PropertiesToIgnore.Count <> 0 then
  2090. begin
  2091. ObjectPropertyIgnoreList.AddStrings(cm.PropertiesToIgnore);
  2092. end
  2093. else
  2094. begin
  2095. // Ignore the entire class
  2096. currentcm := cm;
  2097. break;
  2098. end;
  2099. end;
  2100. end;
  2101. // Then check the global handling instructions
  2102. if currentcm = nil then
  2103. for j := 0 to TP_GlobalClassHandling.Count - 1 do
  2104. begin
  2105. cm := TObject(TP_GlobalClassHandling.Items[j]) as TClassMode;
  2106. if AnObject.InheritsFrom(cm.HClass) then
  2107. begin
  2108. if cm.PropertiesToIgnore.Count <> 0 then
  2109. begin
  2110. ObjectPropertyIgnoreList.AddStrings
  2111. (cm.PropertiesToIgnore);
  2112. end
  2113. else
  2114. begin
  2115. // Ignore the entire class
  2116. currentcm := cm;
  2117. break;
  2118. end;
  2119. end;
  2120. end;
  2121. if currentcm <> nil then
  2122. begin
  2123. ObjectPropertyIgnoreList.Clear;
  2124. // Ignore or use special handler
  2125. if Assigned(currentcm.SpecialHandler) then
  2126. begin
  2127. currentcm.SpecialHandler(AnObject);
  2128. {$IFDEF DXGETTEXTDEBUG}
  2129. DebugWriteln('Special handler activated for ' +
  2130. AnObject.ClassName);
  2131. {$ENDIF}
  2132. end
  2133. else
  2134. begin
  2135. {$IFDEF DXGETTEXTDEBUG}
  2136. DebugWriteln('Ignoring object ' + AnObject.ClassName);
  2137. {$ENDIF}
  2138. end;
  2139. continue;
  2140. end;
  2141. Count := GetPropList(AnObject, PropList);
  2142. try
  2143. for j := 0 to Count - 1 do
  2144. begin
  2145. PropInfo := PropList[j];
  2146. {$IFDEF UNICODE}
  2147. if not(PropInfo^.PropType^.Kind in [tkString, tkLString,
  2148. tkWString, tkClass, tkUString]) then
  2149. {$ELSE}
  2150. if not(PropInfo^.PropType^.Kind in [tkString, tkLString,
  2151. tkWString, tkClass]) then
  2152. {$ENDIF}
  2153. continue;
  2154. UPropName := uppercase(string(PropInfo^.name));
  2155. // Ignore properties that are meant to be ignored
  2156. if ((currentcm = nil) or
  2157. (not currentcm.PropertiesToIgnore.Find(UPropName, i))) and
  2158. (not TP_IgnoreList.Find(Name + '.' + UPropName, i)) and
  2159. (not ObjectPropertyIgnoreList.Find(UPropName, i)) then
  2160. begin
  2161. TranslateProperty(AnObject, PropInfo, TodoList, textdomain);
  2162. end; // if
  2163. end; // for
  2164. finally
  2165. if Count <> 0 then
  2166. FreeMem(PropList);
  2167. end;
  2168. if AnObject is TStrings then
  2169. begin
  2170. if ((AnObject as TStrings).Text <> '') and
  2171. (TP_Retranslator <> nil) then
  2172. (TP_Retranslator as TTP_Retranslator)
  2173. .Remember(AnObject, 'Text', (AnObject as TStrings).Text);
  2174. TranslateStrings(AnObject as TStrings, textdomain);
  2175. end;
  2176. // Check for TCollection
  2177. if AnObject is TCollection then
  2178. begin
  2179. for i := 0 to (AnObject as TCollection).Count - 1 do
  2180. begin
  2181. // Only add the object if it's not totally ignored already
  2182. if not Assigned(currentcm) or
  2183. not AnObject.InheritsFrom(currentcm.HClass) then
  2184. TodoList.AddObject('', (AnObject as TCollection).Items[i]);
  2185. end;
  2186. end;
  2187. if AnObject is TComponent then
  2188. begin
  2189. for i := 0 to TComponent(AnObject).ComponentCount - 1 do
  2190. begin
  2191. comp := TComponent(AnObject).Components[i];
  2192. if (not TP_IgnoreList.Find(uppercase(comp.name), j)) then
  2193. begin
  2194. // Only add the object if it's not totally ignored or translated already
  2195. if not Assigned(currentcm) or
  2196. not AnObject.InheritsFrom(currentcm.HClass) then
  2197. begin
  2198. compmarker := comp.FindComponent('GNUgettextMarker');
  2199. if not Assigned(compmarker) then
  2200. TodoList.AddObject(uppercase(comp.name), comp);
  2201. end;
  2202. end;
  2203. end;
  2204. end;
  2205. end { if AnObject<>nil };
  2206. end { while todolist.count<>0 };
  2207. finally
  2208. FreeAndNil(TodoList);
  2209. FreeAndNil(ObjectPropertyIgnoreList);
  2210. FreeAndNil(DoneList);
  2211. end;
  2212. FreeTP_ClassHandlingItems;
  2213. TP_IgnoreList.Clear;
  2214. TP_Retranslator := nil;
  2215. {$IFDEF DXGETTEXTDEBUG}
  2216. DebugWriteln
  2217. ('----------------------------------------------------------------------');
  2218. {$ENDIF}
  2219. end;
  2220. procedure TGnuGettextInstance.UnregisterWhenNewLanguageListener
  2221. (Listener: IGnuGettextInstanceWhenNewLanguageListener);
  2222. begin
  2223. fWhenNewLanguageListeners.Remove(Listener);
  2224. end;
  2225. procedure TGnuGettextInstance.UseLanguage(LanguageCode: LanguageString);
  2226. var
  2227. i, p: Integer;
  2228. dom: TDomain;
  2229. l2: string;
  2230. begin
  2231. {$IFDEF DXGETTEXTDEBUG}
  2232. DebugWriteln('UseLanguage(''' + LanguageCode + '''); called');
  2233. {$ENDIF}
  2234. if LanguageCode = '' then
  2235. begin
  2236. LanguageCode := GGGetEnvironmentVariable('LANG');
  2237. {$IFDEF DXGETTEXTDEBUG}
  2238. DebugWriteln('LANG env variable is ''' + LanguageCode + '''.');
  2239. {$ENDIF}
  2240. {$IFDEF MSWINDOWS}
  2241. if LanguageCode = '' then
  2242. begin
  2243. LanguageCode := GetWindowsLanguage;
  2244. {$IFDEF DXGETTEXTDEBUG}
  2245. DebugWriteln('Found Windows language code to be ''' +
  2246. LanguageCode + '''.');
  2247. {$ENDIF}
  2248. end;
  2249. {$ENDIF}
  2250. p := pos('.', LanguageCode);
  2251. if p <> 0 then
  2252. LanguageCode := LeftStr(LanguageCode, p - 1);
  2253. {$IFDEF DXGETTEXTDEBUG}
  2254. DebugWriteln('Language code that will be set is ''' +
  2255. LanguageCode + '''.');
  2256. {$ENDIF}
  2257. end;
  2258. curlang := LanguageCode;
  2259. for i := 0 to domainlist.Count - 1 do
  2260. begin
  2261. dom := domainlist.Objects[i] as TDomain;
  2262. dom.SetLanguageCode(curlang);
  2263. end;
  2264. l2 := lowercase(LeftStr(curlang, 2));
  2265. if (l2 = 'en') or (l2 = 'de') then
  2266. curGetPluralForm := GetPluralForm2EN
  2267. else if (l2 = 'hu') or (l2 = 'ko') or (l2 = 'zh') or (l2 = 'ja') or
  2268. (l2 = 'tr') then
  2269. curGetPluralForm := GetPluralForm1
  2270. else if (l2 = 'fr') or (l2 = 'fa') or (lowercase(curlang) = 'pt_br')
  2271. then
  2272. curGetPluralForm := GetPluralForm2FR
  2273. else if (l2 = 'lv') then
  2274. curGetPluralForm := GetPluralForm3LV
  2275. else if (l2 = 'ga') then
  2276. curGetPluralForm := GetPluralForm3GA
  2277. else if (l2 = 'lt') then
  2278. curGetPluralForm := GetPluralForm3LT
  2279. else if (l2 = 'ru') or (l2 = 'uk') or (l2 = 'hr') then
  2280. curGetPluralForm := GetPluralForm3RU
  2281. else if (l2 = 'cs') or (l2 = 'sk') then
  2282. curGetPluralForm := GetPluralForm3SK
  2283. else if (l2 = 'pl') then
  2284. curGetPluralForm := GetPluralForm3PL
  2285. else if (l2 = 'sl') then
  2286. curGetPluralForm := GetPluralForm4SL
  2287. else
  2288. begin
  2289. curGetPluralForm := GetPluralForm2EN;
  2290. {$IFDEF DXGETTEXTDEBUG}
  2291. DebugWriteln
  2292. ('Plural form for the language was not found. English plurality system assumed.');
  2293. {$ENDIF}
  2294. end;
  2295. WhenNewLanguage(curlang);
  2296. {$IFDEF DXGETTEXTDEBUG}
  2297. DebugWriteln('');
  2298. {$ENDIF}
  2299. end;
  2300. procedure TGnuGettextInstance.TranslateStrings(sl: TStrings;
  2301. const textdomain: DomainString);
  2302. var
  2303. Line: string;
  2304. i: Integer;
  2305. s: TStringList;
  2306. slAsTStringList: TStringList;
  2307. originalOwnsObjects: boolean;
  2308. begin
  2309. if sl.Count > 0 then
  2310. begin
  2311. // From D2009 onward, the TStringList class has a OwnsObjects property, just like
  2312. // TObjectList has. This means that when we will be calling Clear on the given
  2313. // list in the sl parameter, we could destroy the objects it contains.
  2314. // To avoid this we must disable OwnsObjects while we replace the strings, but
  2315. // only if sl is a TStringList instance and if using Delphi 2009 or upper.
  2316. originalOwnsObjects := false; // avoid warning
  2317. if sl is TStringList then
  2318. slAsTStringList := TStringList(sl)
  2319. else
  2320. slAsTStringList := nil;
  2321. sl.BeginUpdate;
  2322. try
  2323. s := TStringList.Create;
  2324. try
  2325. // don't use Assign here as it will propagate the Sorted property (among others)
  2326. // in versions of Delphi from Delphi XE ownard
  2327. s.AddStrings(sl);
  2328. for i := 0 to s.Count - 1 do
  2329. begin
  2330. Line := s.Strings[i];
  2331. if Line <> '' then
  2332. if textdomain = '' then
  2333. s.Strings[i] := ComponentGettext(Line)
  2334. else
  2335. s.Strings[i] := dgettext(textdomain, Line);
  2336. end;
  2337. if Assigned(slAsTStringList) then
  2338. begin
  2339. originalOwnsObjects := slAsTStringList.OwnsObjects;
  2340. slAsTStringList.OwnsObjects := false;
  2341. end;
  2342. try
  2343. // same here, we don't want to modify the properties of the orignal string list
  2344. sl.Clear;
  2345. sl.AddStrings(s);
  2346. finally
  2347. if Assigned(slAsTStringList) then
  2348. slAsTStringList.OwnsObjects := originalOwnsObjects;
  2349. end;
  2350. finally
  2351. FreeAndNil(s);
  2352. end;
  2353. finally
  2354. sl.EndUpdate;
  2355. end;
  2356. end;
  2357. end;
  2358. function TGnuGettextInstance.GetTranslatorNameAndEmail
  2359. : TranslatedUnicodeString;
  2360. begin
  2361. Result := GetTranslationProperty('LAST-TRANSLATOR');
  2362. end;
  2363. function TGnuGettextInstance.GetTranslationProperty(const propertyname
  2364. : ComponentNameString): TranslatedUnicodeString;
  2365. begin
  2366. Result := Getdomain(curmsgdomain, DefaultDomainDirectory, curlang)
  2367. .GetTranslationProperty(propertyname);
  2368. end;
  2369. function TGnuGettextInstance.dngettext(const szDomain: DomainString;
  2370. const singular, plural: MsgIdString; Number: Integer)
  2371. : TranslatedUnicodeString;
  2372. var
  2373. org: MsgIdString;
  2374. trans: TranslatedUnicodeString;
  2375. idx: Integer;
  2376. p: Integer;
  2377. begin
  2378. {$IFDEF DXGETTEXTDEBUG}
  2379. DebugWriteln('dngettext translation (domain ' + szDomain +
  2380. ', number is ' + IntToStr(Number) + ') of ' + singular + '/'
  2381. + plural);
  2382. {$ENDIF}
  2383. org := singular + #0 + plural;
  2384. trans := dgettext(szDomain, org);
  2385. if org = trans then
  2386. begin
  2387. {$IFDEF DXGETTEXTDEBUG}
  2388. DebugWriteln
  2389. ('Translation was equal to english version. English plural forms assumed.');
  2390. {$ENDIF}
  2391. idx := GetPluralForm2EN(Number)
  2392. end
  2393. else
  2394. idx := curGetPluralForm(Number);
  2395. {$IFDEF DXGETTEXTDEBUG}
  2396. DebugWriteln('Index ' + IntToStr(idx) + ' will be used');
  2397. {$ENDIF}
  2398. while True do
  2399. begin
  2400. p := pos(#0, trans);
  2401. if p = 0 then
  2402. begin
  2403. {$IFDEF DXGETTEXTDEBUG}
  2404. DebugWriteln('Last translation used: ' + utf8encode(trans));
  2405. {$ENDIF}
  2406. Result := trans;
  2407. exit;
  2408. end;
  2409. if idx = 0 then
  2410. begin
  2411. {$IFDEF DXGETTEXTDEBUG}
  2412. DebugWriteln('Translation found: ' + utf8encode(trans));
  2413. {$ENDIF}
  2414. Result := LeftStr(trans, p - 1);
  2415. exit;
  2416. end;
  2417. delete(trans, 1, p);
  2418. dec(idx);
  2419. end;
  2420. end;
  2421. function TGnuGettextInstance.dngettext_NoExtract(const szDomain
  2422. : DomainString; const singular, plural: MsgIdString; Number: Integer)
  2423. : TranslatedUnicodeString;
  2424. begin
  2425. // This one is very useful for translating text in variables.
  2426. // This can sometimes be necessary, and by using this function,
  2427. // the source code scanner will not trigger warnings.
  2428. Result := dngettext(szDomain, singular, plural, Number);
  2429. end;
  2430. {$IFNDEF UNICODE}
  2431. function TGnuGettextInstance.ngettext(const singular, plural: AnsiString;
  2432. Number: Integer): TranslatedUnicodeString;
  2433. begin
  2434. Result := dngettext(curmsgdomain, singular, plural, Number);
  2435. end;
  2436. {$ENDIF}
  2437. function TGnuGettextInstance.ngettext(const singular, plural: MsgIdString;
  2438. Number: Integer): TranslatedUnicodeString;
  2439. begin
  2440. Result := dngettext(curmsgdomain, singular, plural, Number);
  2441. end;
  2442. function TGnuGettextInstance.ngettext_NoExtract(const singular,
  2443. plural: MsgIdString; Number: Integer): TranslatedUnicodeString;
  2444. begin
  2445. // This one is very useful for translating text in variables.
  2446. // This can sometimes be necessary, and by using this function,
  2447. // the source code scanner will not trigger warnings.
  2448. Result := ngettext(singular, plural, Number);
  2449. end;
  2450. procedure TGnuGettextInstance.WhenNewDomain(const textdomain
  2451. : DomainString);
  2452. begin
  2453. // This is meant to be empty.
  2454. end;
  2455. procedure TGnuGettextInstance.WhenNewLanguage(const LanguageID
  2456. : LanguageString);
  2457. var
  2458. i: Integer;
  2459. begin
  2460. for i := 0 to fWhenNewLanguageListeners.Count - 1 do
  2461. IGnuGettextInstanceWhenNewLanguageListener
  2462. (fWhenNewLanguageListeners[i]).WhenNewLanguage(LanguageID);
  2463. end;
  2464. procedure TGnuGettextInstance.WhenNewDomainDirectory(const textdomain
  2465. : DomainString; const Directory: FilenameString);
  2466. begin
  2467. // This is meant to be empty.
  2468. end;
  2469. procedure TGnuGettextInstance.GetListOfLanguages
  2470. (const domain: DomainString; list: TStrings);
  2471. begin
  2472. Getdomain(domain, DefaultDomainDirectory, curlang)
  2473. .GetListOfLanguages(list);
  2474. end;
  2475. procedure TGnuGettextInstance.bindtextdomainToFile(const szDomain
  2476. : DomainString; const filename: FilenameString);
  2477. begin
  2478. {$IFDEF DXGETTEXTDEBUG}
  2479. DebugWriteln('Text domain "' + szDomain +
  2480. '" is now bound to file named "' + filename + '"');
  2481. {$ENDIF}
  2482. Getdomain(szDomain, DefaultDomainDirectory, curlang)
  2483. .SetFilename(filename);
  2484. end;
  2485. procedure TGnuGettextInstance.DebugLogPause(PauseEnabled: boolean);
  2486. begin
  2487. {$IFDEF DXGETTEXTDEBUG}
  2488. DebugLogOutputPaused := PauseEnabled;
  2489. {$ENDIF}
  2490. end;
  2491. procedure TGnuGettextInstance.DebugLogToFile(const filename
  2492. : FilenameString; append: boolean = false);
  2493. {$IFDEF DXGETTEXTDEBUG}
  2494. var
  2495. fs: TFileStream;
  2496. marker: AnsiString;
  2497. {$ENDIF}
  2498. begin
  2499. {$IFDEF DXGETTEXTDEBUG}
  2500. // Create the file if needed
  2501. if (not FileExists(filename)) or (not append) then
  2502. fileclose(filecreate(filename));
  2503. // Open file
  2504. fs := TFileStream.Create(filename, fmOpenWrite or fmShareDenyWrite);
  2505. if append then
  2506. fs.Seek(0, soFromEnd);
  2507. // Write header if appending
  2508. if fs.Position <> 0 then
  2509. begin
  2510. marker := sLinebreak +
  2511. '==========================================================================='
  2512. + sLinebreak;
  2513. fs.WriteBuffer(marker[1], length(marker));
  2514. end;
  2515. // Copy the memorystream contents to the file
  2516. if DebugLog <> nil then
  2517. begin
  2518. DebugLog.Seek(0, soFromBeginning);
  2519. fs.CopyFrom(DebugLog, 0);
  2520. end;
  2521. // Make DebugLog point to the filestream
  2522. FreeAndNil(DebugLog);
  2523. DebugLog := fs;
  2524. {$ENDIF}
  2525. end;
  2526. {$IFDEF DXGETTEXTDEBUG}
  2527. procedure TGnuGettextInstance.DebugWriteln(Line: AnsiString);
  2528. Var
  2529. Discard: boolean;
  2530. begin
  2531. Assert(DebugLogCS <> nil);
  2532. Assert(DebugLog <> nil);
  2533. DebugLogCS.BeginWrite;
  2534. try
  2535. if DebugLogOutputPaused then
  2536. exit;
  2537. if Assigned(fOnDebugLine) then
  2538. begin
  2539. Discard := True;
  2540. fOnDebugLine(self, Line, Discard);
  2541. If Discard then
  2542. exit;
  2543. end;
  2544. Line := Line + sLinebreak;
  2545. // Ensure that memory usage doesn't get too big.
  2546. if (DebugLog is TMemoryStream) and (DebugLog.Position > 1000000) then
  2547. begin
  2548. Line := sLinebreak + sLinebreak + sLinebreak + sLinebreak +
  2549. sLinebreak +
  2550. 'Debug log halted because memory usage grew too much.' +
  2551. sLinebreak +
  2552. 'Specify a filename to store the debug log in or disable debug loggin in gnugettext.pas.'
  2553. + sLinebreak + sLinebreak + sLinebreak + sLinebreak + sLinebreak;
  2554. DebugLogOutputPaused := True;
  2555. end;
  2556. DebugLog.WriteBuffer(Line[1], length(Line));
  2557. finally
  2558. DebugLogCS.EndWrite;
  2559. end;
  2560. end;
  2561. {$ENDIF}
  2562. function TGnuGettextInstance.Getdomain(const domain: DomainString;
  2563. const DefaultDomainDirectory: FilenameString;
  2564. const curlang: LanguageString): TDomain;
  2565. // Retrieves the TDomain object for the specified domain.
  2566. // Creates one, if none there, yet.
  2567. var
  2568. idx: Integer;
  2569. begin
  2570. idx := domainlist.IndexOf(domain);
  2571. if idx = -1 then
  2572. begin
  2573. Result := TDomain.Create;
  2574. {$IFDEF DXGETTEXTDEBUG}
  2575. Result.DebugLogger := DebugWriteln;
  2576. {$ENDIF}
  2577. Result.domain := domain;
  2578. Result.Directory := DefaultDomainDirectory;
  2579. Result.SetLanguageCode(curlang);
  2580. domainlist.AddObject(domain, Result);
  2581. end
  2582. else
  2583. begin
  2584. Result := domainlist.Objects[idx] as TDomain;
  2585. end;
  2586. end;
  2587. function TGnuGettextInstance.LoadResString(ResStringRec: PResStringRec)
  2588. : UnicodeString;
  2589. {$IFDEF MSWINDOWS}
  2590. var
  2591. Len: Integer;
  2592. {$IFDEF UNICODE}
  2593. Buffer: array [0 .. 1023] of widechar;
  2594. {$ELSE}
  2595. Buffer: array [0 .. 1023] of ansichar;
  2596. {$ENDIF}
  2597. {$ENDIF}
  2598. {$IFDEF LINUX }
  2599. const
  2600. ResStringTableLen = 16;
  2601. type
  2602. ResStringTable = array [0 .. ResStringTableLen - 1] of LongWord;
  2603. var
  2604. Handle: TResourceHandle;
  2605. Tab: ^ResStringTable;
  2606. ResMod: HModule;
  2607. {$ENDIF }
  2608. begin
  2609. if ResStringRec = nil then
  2610. exit;
  2611. if ResStringRec.Identifier >= 64 * 1024 then
  2612. begin
  2613. {$IFDEF DXGETTEXTDEBUG}
  2614. DebugWriteln
  2615. ('LoadResString was given an invalid ResStringRec.Identifier');
  2616. {$ENDIF}
  2617. Result := 'ERROR';
  2618. exit;
  2619. end
  2620. else
  2621. begin
  2622. {$IFDEF LINUX}
  2623. // This works with Unicode if the Linux has utf-8 character set
  2624. // Result:=System.LoadResString(ResStringRec);
  2625. ResMod := FindResourceHInstance(ResStringRec^.Module^);
  2626. Handle := FindResource(ResMod,
  2627. PAnsiChar(ResStringRec^.Identifier div ResStringTableLen),
  2628. PAnsiChar(6)); // RT_STRING
  2629. Tab := pointer(LoadResource(ResMod, Handle));
  2630. if Tab = nil then
  2631. Result := ''
  2632. else
  2633. Result := PWideChar(PAnsiChar(Tab) +
  2634. Tab[ResStringRec^.Identifier mod ResStringTableLen]);
  2635. {$ENDIF}
  2636. {$IFDEF MSWINDOWS}
  2637. if not Win32PlatformIsUnicode then
  2638. begin
  2639. SetString(Result, Buffer,
  2640. LoadString(FindResourceHInstance(ResStringRec.Module^),
  2641. ResStringRec.Identifier, Buffer, SizeOf(Buffer)))
  2642. end
  2643. else
  2644. begin
  2645. Result := '';
  2646. Len := 0;
  2647. While length(Result) <= Len + 1 do
  2648. begin
  2649. if length(Result) = 0 then
  2650. SetLength(Result, 1024)
  2651. else
  2652. SetLength(Result, length(Result) * 2);
  2653. Len := LoadStringW(FindResourceHInstance(ResStringRec.Module^),
  2654. ResStringRec.Identifier, PWideChar(Result), length(Result));
  2655. end;
  2656. SetLength(Result, Len);
  2657. end;
  2658. {$ENDIF}
  2659. end;
  2660. {$IFDEF DXGETTEXTDEBUG}
  2661. DebugWriteln('Loaded resourcestring: ' + utf8encode(Result));
  2662. {$ENDIF}
  2663. Result := ResourceStringGettext(Result);
  2664. end;
  2665. procedure TGnuGettextInstance.RegisterWhenNewLanguageListener
  2666. (Listener: IGnuGettextInstanceWhenNewLanguageListener);
  2667. begin
  2668. fWhenNewLanguageListeners.Add(Listener);
  2669. end;
  2670. procedure TGnuGettextInstance.RetranslateComponent(AnObject: TComponent;
  2671. const textdomain: DomainString);
  2672. var
  2673. comp: TGnuGettextComponentMarker;
  2674. begin
  2675. {$IFDEF DXGETTEXTDEBUG}
  2676. DebugWriteln
  2677. ('======================================================================');
  2678. DebugWriteln
  2679. ('RetranslateComponent() was called for a component with name ' +
  2680. AnObject.name + '.');
  2681. {$ENDIF}
  2682. comp := AnObject.FindComponent('GNUgettextMarker')
  2683. as TGnuGettextComponentMarker;
  2684. if comp = nil then
  2685. begin
  2686. {$IFDEF DXGETTEXTDEBUG}
  2687. DebugWriteln
  2688. ('Retranslate was called on an object that has not been translated before. An Exception is being raised.');
  2689. {$ENDIF}
  2690. raise EGGProgrammingError.Create
  2691. ('Retranslate was called on an object that has not been translated before. Please use TranslateComponent() before RetranslateComponent().');
  2692. end
  2693. else
  2694. begin
  2695. // *** if param ReReadMoFileOnSameLanguage is set, use the ReTranslate
  2696. // function nevertheless if the current language is the same like the
  2697. // new (-> reread the current .mo-file from the file system).
  2698. if ReReadMoFileOnSameLanguage or (comp.LastLanguage <> curlang) then
  2699. begin
  2700. {$IFDEF DXGETTEXTDEBUG}
  2701. DebugWriteln('The retranslator is being executed.');
  2702. {$ENDIF}
  2703. comp.Retranslator.Execute;
  2704. end
  2705. else
  2706. begin
  2707. {$IFDEF DXGETTEXTDEBUG}
  2708. DebugWriteln
  2709. ('The language has not changed. The retranslator is not executed.');
  2710. {$ENDIF}
  2711. end;
  2712. end;
  2713. comp.LastLanguage := curlang;
  2714. {$IFDEF DXGETTEXTDEBUG}
  2715. DebugWriteln
  2716. ('======================================================================');
  2717. {$ENDIF}
  2718. end;
  2719. procedure TGnuGettextInstance.TP_IgnoreClass(IgnClass: TClass);
  2720. var
  2721. cm: TClassMode;
  2722. i: Integer;
  2723. begin
  2724. for i := 0 to TP_ClassHandling.Count - 1 do
  2725. begin
  2726. cm := TObject(TP_ClassHandling.Items[i]) as TClassMode;
  2727. if cm.HClass = IgnClass then
  2728. raise EGGProgrammingError.Create
  2729. ('You cannot add a class to the ignore list that is already on that list: '
  2730. + IgnClass.ClassName + '.');
  2731. if IgnClass.InheritsFrom(cm.HClass) then
  2732. begin
  2733. // This is the place to insert this class
  2734. cm := TClassMode.Create;
  2735. cm.HClass := IgnClass;
  2736. TP_ClassHandling.insert(i, cm);
  2737. {$IFDEF DXGETTEXTDEBUG}
  2738. DebugWriteln('Locally, class ' + IgnClass.ClassName +
  2739. ' is being ignored.');
  2740. {$ENDIF}
  2741. exit;
  2742. end;
  2743. end;
  2744. cm := TClassMode.Create;
  2745. cm.HClass := IgnClass;
  2746. TP_ClassHandling.Add(cm);
  2747. {$IFDEF DXGETTEXTDEBUG}
  2748. DebugWriteln('Locally, class ' + IgnClass.ClassName +
  2749. ' is being ignored.');
  2750. {$ENDIF}
  2751. end;
  2752. procedure TGnuGettextInstance.TP_IgnoreClassProperty(IgnClass: TClass;
  2753. propertyname: ComponentNameString);
  2754. var
  2755. cm: TClassMode;
  2756. i: Integer;
  2757. begin
  2758. propertyname := uppercase(propertyname);
  2759. for i := 0 to TP_ClassHandling.Count - 1 do
  2760. begin
  2761. cm := TObject(TP_ClassHandling.Items[i]) as TClassMode;
  2762. if cm.HClass = IgnClass then
  2763. begin
  2764. if Assigned(cm.SpecialHandler) then
  2765. raise EGGProgrammingError.Create
  2766. ('You cannot ignore a class property for a class that has a handler set.');
  2767. cm.PropertiesToIgnore.Add(propertyname);
  2768. {$IFDEF DXGETTEXTDEBUG}
  2769. DebugWriteln('Globally, the ' + propertyname + ' property of class '
  2770. + IgnClass.ClassName + ' is being ignored.');
  2771. {$ENDIF}
  2772. exit;
  2773. end;
  2774. if IgnClass.InheritsFrom(cm.HClass) then
  2775. begin
  2776. // This is the place to insert this class
  2777. cm := TClassMode.Create;
  2778. cm.HClass := IgnClass;
  2779. cm.PropertiesToIgnore.Add(propertyname);
  2780. TP_ClassHandling.insert(i, cm);
  2781. {$IFDEF DXGETTEXTDEBUG}
  2782. DebugWriteln('Locally, the ' + propertyname + ' property of class '
  2783. + IgnClass.ClassName + ' is being ignored.');
  2784. {$ENDIF}
  2785. exit;
  2786. end;
  2787. end;
  2788. cm := TClassMode.Create;
  2789. cm.HClass := IgnClass;
  2790. cm.PropertiesToIgnore.Add(propertyname);
  2791. TP_GlobalClassHandling.Add(cm);
  2792. {$IFDEF DXGETTEXTDEBUG}
  2793. DebugWriteln('Locally, the ' + propertyname + ' property of class ' +
  2794. IgnClass.ClassName + ' is being ignored.');
  2795. {$ENDIF}
  2796. end;
  2797. procedure TGnuGettextInstance.FreeTP_ClassHandlingItems;
  2798. begin
  2799. while TP_ClassHandling.Count <> 0 do
  2800. begin
  2801. TObject(TP_ClassHandling.Items[0]).Free;
  2802. TP_ClassHandling.delete(0);
  2803. end;
  2804. end;
  2805. {$IFNDEF UNICODE}
  2806. function TGnuGettextInstance.ansi2wideDTCP(const s: AnsiString)
  2807. : MsgIdString;
  2808. {$IFDEF MSWindows}
  2809. var
  2810. Len: Integer;
  2811. {$ENDIF}
  2812. begin
  2813. {$IFDEF MSWindows}
  2814. if DesignTimeCodePage = CP_ACP then
  2815. begin
  2816. // No design-time codepage specified. Using runtime codepage instead.
  2817. {$ENDIF}
  2818. Result := s;
  2819. {$IFDEF MSWindows}
  2820. end
  2821. else
  2822. begin
  2823. Len := length(s);
  2824. if Len = 0 then
  2825. Result := ''
  2826. else
  2827. begin
  2828. SetLength(Result, Len);
  2829. Len := MultiByteToWideChar(DesignTimeCodePage, 0, PAnsiChar(s), Len,
  2830. PWideChar(Result), Len);
  2831. if Len = 0 then
  2832. raise EGGAnsi2WideConvError.Create
  2833. ('Cannot convert string to widestring:' + sLinebreak + s);
  2834. SetLength(Result, Len);
  2835. end;
  2836. end;
  2837. {$ENDIF}
  2838. end;
  2839. {$ENDIF}
  2840. {$IFNDEF UNICODE}
  2841. function TGnuGettextInstance.dngettext(const szDomain: DomainString;
  2842. const singular, plural: AnsiString; Number: Integer)
  2843. : TranslatedUnicodeString;
  2844. begin
  2845. Result := dngettext(szDomain, ansi2wideDTCP(singular),
  2846. ansi2wideDTCP(plural), Number);
  2847. end;
  2848. {$ENDIF}
  2849. { TClassMode }
  2850. constructor TClassMode.Create;
  2851. begin
  2852. PropertiesToIgnore := TStringList.Create;
  2853. PropertiesToIgnore.Sorted := True;
  2854. PropertiesToIgnore.Duplicates := dupError;
  2855. PropertiesToIgnore.CaseSensitive := false;
  2856. end;
  2857. destructor TClassMode.Destroy;
  2858. begin
  2859. FreeAndNil(PropertiesToIgnore);
  2860. inherited;
  2861. end;
  2862. { TFileLocator }
  2863. function TFileLocator.FindSignaturePos(const signature: RawByteString;
  2864. str: TFileStream): int64;
  2865. // Finds the position of signature in the file.
  2866. const
  2867. bufsize = 100000;
  2868. var
  2869. a: RawByteString;
  2870. b: RawByteString;
  2871. Offset: Integer;
  2872. rd, p: Integer;
  2873. begin
  2874. if signature = '' then
  2875. begin
  2876. Result := 0;
  2877. exit;
  2878. end;
  2879. Offset := 0;
  2880. str.Seek(0, soFromBeginning);
  2881. SetLength(a, bufsize);
  2882. SetLength(b, bufsize);
  2883. str.Read(a[1], bufsize);
  2884. while True do
  2885. begin
  2886. rd := str.Read(b[1], bufsize);
  2887. p := pos(signature, a + b);
  2888. if (p <> 0) then
  2889. begin // do not check p < bufsize+100 here!
  2890. Result := Offset + p - 1;
  2891. exit;
  2892. end;
  2893. if rd <> bufsize then
  2894. begin
  2895. // Prematurely ended without finding anything
  2896. Result := 0;
  2897. exit;
  2898. end;
  2899. a := b;
  2900. Offset := Offset + bufsize;
  2901. end;
  2902. Result := 0;
  2903. end;
  2904. // Changed to "Analyze" with old signature to be compatible to older programs
  2905. // and to the assemble routine in GgtTranslate
  2906. // JR - 2012-09-10
  2907. procedure TFileLocator.Analyze;
  2908. var
  2909. s: AnsiString;
  2910. i: Integer;
  2911. Offset: int64;
  2912. fs: TFileStream;
  2913. fi: TEmbeddedFileInfo;
  2914. filename: AnsiString;
  2915. // change from FilenameString to AnsiString, JR - 2010-04-10
  2916. begin
  2917. // "ggassemble" will search for this GUI and replace the trailing #0s by a pointer
  2918. // to the begin of the embedded mo files
  2919. s := '6637DB2E-62E1-4A60-AC19-C23867046A89'#0#0#0#0#0#0#0#0; // constant
  2920. s := MidStr(s, length(s) - 7, 8);
  2921. Offset := 0;
  2922. for i := 8 downto 1 do
  2923. Offset := Offset shl 8 + ord(s[i]);
  2924. if Offset = 0 then
  2925. exit;
  2926. basedirectory := extractfilepath(ExecutableFilename);
  2927. try
  2928. fs := TFileStream.Create(ExecutableFilename, fmOpenRead or
  2929. fmShareDenyNone);
  2930. try
  2931. while True do
  2932. begin
  2933. fs.Seek(Offset, soFromBeginning);
  2934. Offset := ReadInt64(fs);
  2935. if Offset = 0 then
  2936. exit;
  2937. fi := TEmbeddedFileInfo.Create;
  2938. try
  2939. fi.Offset := ReadInt64(fs);
  2940. fi.Size := ReadInt64(fs);
  2941. SetLength(filename, Offset - fs.Position);
  2942. fs.ReadBuffer(filename[1], Offset - fs.Position);
  2943. filename := trim(filename);
  2944. if PreferExternal and System.SysUtils.FileExists
  2945. (basedirectory + filename) then
  2946. begin
  2947. // Disregard the internal version and use the external version instead
  2948. FreeAndNil(fi);
  2949. end
  2950. else
  2951. filelist.AddObject(filename, fi);
  2952. except
  2953. FreeAndNil(fi);
  2954. raise;
  2955. end;
  2956. end;
  2957. finally
  2958. FreeAndNil(fs);
  2959. end;
  2960. except
  2961. {$IFDEF DXGETTEXTDEBUG}
  2962. raise;
  2963. {$ENDIF}
  2964. end;
  2965. end;
  2966. (* procedure TFileLocator.Analyze;
  2967. var
  2968. HeaderSize,
  2969. PrefixSize: Integer;
  2970. dummysig,
  2971. headerpre,
  2972. headerbeg,
  2973. headerend:RawByteString;
  2974. i:integer;
  2975. headerbeginpos,
  2976. headerendpos:integer;
  2977. offset,
  2978. tableoffset:int64;
  2979. fs:TFileStream;
  2980. fi:TEmbeddedFileInfo;
  2981. filename:FilenameString;
  2982. filename8bit:RawByteString;
  2983. const
  2984. // DetectionSignature: used solely to detect gnugettext usage by assemble
  2985. DetectionSignature: array[0..35] of AnsiChar='2E23E563-31FA-4C24-B7B3-90BE720C6B1A';
  2986. // Embedded Header Begin Signature (without dynamic prefix written by assemble)
  2987. BeginHeaderSignature: array[0..35] of AnsiChar='BD7F1BE4-9FCF-4E3A-ABA7-3443D11AB362';
  2988. // Embedded Header End Signature (without dynamic prefix written by assemble)
  2989. EndHeaderSignature: array[0..35] of AnsiChar='1C58841C-D8A0-4457-BF54-D8315D4CF49D';
  2990. // Assemble Prefix (do not put before the Header Signatures!)
  2991. SignaturePrefix: array[0..2] of AnsiChar='DXG'; // written from assemble
  2992. begin
  2993. // Attn: Ensure all Signatures have the same size!
  2994. HeaderSize := High(BeginHeaderSignature) - Low(BeginHeaderSignature) + 1;
  2995. PrefixSize := High(SignaturePrefix) - Low(SignaturePrefix) + 1;
  2996. // dummy usage of DetectionSignature (otherwise not compiled into exe)
  2997. SetLength(dummysig, HeaderSize);
  2998. for i := 0 to HeaderSize-1 do
  2999. dummysig[i+1] := DetectionSignature[i];
  3000. // copy byte by byte (D2009+ compatible)
  3001. SetLength(headerpre, PrefixSize);
  3002. for i:= 0 to PrefixSize-1 do
  3003. headerpre[i+1] := SignaturePrefix[i];
  3004. SetLength(headerbeg, HeaderSize);
  3005. for i:= 0 to HeaderSize-1 do
  3006. headerbeg[i+1] := BeginHeaderSignature[i];
  3007. SetLength(headerend, HeaderSize);
  3008. for i:= 0 to HeaderSize-1 do
  3009. headerend[i+1] := EndHeaderSignature[i];
  3010. BaseDirectory:=ExtractFilePath(ExecutableFilename);
  3011. try
  3012. fs:=TFileStream.Create(ExecutableFilename,fmOpenRead or fmShareDenyNone);
  3013. try
  3014. // try to find new header begin and end signatures
  3015. headerbeginpos := FindSignaturePos(headerpre+headerbeg, fs);
  3016. headerendpos := FindSignaturePos(headerpre+headerend, fs);
  3017. if (headerbeginpos > 0) and (headerendpos > 0) then
  3018. begin
  3019. // adjust positions (to the end of each signature)
  3020. headerbeginpos := headerbeginpos + HeaderSize + PrefixSize;
  3021. // get file table offset (8 byte, stored directly before the end header)
  3022. fs.Seek(headerendpos - 8, soFromBeginning);
  3023. // get relative offset and convert to absolute offset during runtime
  3024. tableoffset := headerbeginpos + ReadInt64(fs);
  3025. // go to beginning of embedded block
  3026. fs.Seek(headerbeginpos, soFromBeginning);
  3027. offset := tableoffset;
  3028. Assert(sizeof(offset)=8);
  3029. while (true) and (fs.Position<headerendpos) do begin
  3030. fs.Seek(offset,soFromBeginning);
  3031. offset:=ReadInt64(fs);
  3032. if offset=0 then
  3033. exit;
  3034. offset:=headerbeginpos+offset;
  3035. fi:=TEmbeddedFileInfo.Create;
  3036. try
  3037. // get embedded file info (adjusting dynamic to real offsets now)
  3038. fi.Offset:=headerbeginpos+ReadInt64(fs);
  3039. fi.Size:=ReadInt64(fs);
  3040. SetLength (filename8bit, offset-fs.position);
  3041. fs.ReadBuffer (filename8bit[1], offset-fs.position);
  3042. filename:=trim(utf8decode(filename8bit));
  3043. if PreferExternal and sysutils.fileexists(basedirectory+filename) then begin
  3044. // Disregard the internal version and use the external version instead
  3045. FreeAndNil (fi);
  3046. end else
  3047. filelist.AddObject(filename,fi);
  3048. except
  3049. FreeAndNil (fi);
  3050. raise;
  3051. end;
  3052. end;
  3053. end;
  3054. finally
  3055. FreeAndNil (fs);
  3056. end;
  3057. except
  3058. {$ifdef DXGETTEXTDEBUG}
  3059. raise;
  3060. {$endif}
  3061. end;
  3062. end; *)
  3063. constructor TFileLocator.Create;
  3064. begin
  3065. MoFilesCS := TMultiReadExclusiveWriteSynchronizer.Create;
  3066. MoFiles := TStringList.Create;
  3067. filelist := TStringList.Create;
  3068. {$IFDEF LINUX}
  3069. filelist.Duplicates := dupError;
  3070. filelist.CaseSensitive := True;
  3071. {$ENDIF}
  3072. MoFiles.Sorted := True;
  3073. MoFiles.Duplicates := dupError;
  3074. MoFiles.CaseSensitive := false;
  3075. {$IFDEF MSWINDOWS}
  3076. filelist.Duplicates := dupError;
  3077. filelist.CaseSensitive := false;
  3078. {$ENDIF}
  3079. filelist.Sorted := True;
  3080. end;
  3081. destructor TFileLocator.Destroy;
  3082. begin
  3083. while filelist.Count <> 0 do
  3084. begin
  3085. filelist.Objects[0].Free;
  3086. filelist.delete(0);
  3087. end;
  3088. FreeAndNil(filelist);
  3089. FreeAndNil(MoFiles);
  3090. FreeAndNil(MoFilesCS);
  3091. inherited;
  3092. end;
  3093. function TFileLocator.FileExists(filename: FilenameString): boolean;
  3094. var
  3095. idx: Integer;
  3096. begin
  3097. if LeftStr(filename, length(basedirectory)) = basedirectory then
  3098. begin
  3099. // Cut off basedirectory if the file is located beneath that base directory
  3100. filename := MidStr(filename, length(basedirectory) + 1, maxint);
  3101. end;
  3102. Result := filelist.Find(filename, idx);
  3103. end;
  3104. function TFileLocator.GetMoFile(filename: FilenameString;
  3105. DebugLogger: TDebugLogger): TMoFile;
  3106. var
  3107. fi: TEmbeddedFileInfo;
  3108. idx: Integer;
  3109. idxname: FilenameString;
  3110. Offset, Size: int64;
  3111. realfilename: FilenameString;
  3112. begin
  3113. // Find real filename
  3114. Offset := 0;
  3115. Size := 0;
  3116. realfilename := filename;
  3117. if LeftStr(filename, length(basedirectory)) = basedirectory then
  3118. begin
  3119. filename := MidStr(filename, length(basedirectory) + 1, maxint);
  3120. idx := filelist.IndexOf(filename);
  3121. if idx <> -1 then
  3122. begin
  3123. fi := filelist.Objects[idx] as TEmbeddedFileInfo;
  3124. realfilename := ExecutableFilename;
  3125. Offset := fi.Offset;
  3126. Size := fi.Size;
  3127. {$IFDEF DXGETTEXTDEBUG}
  3128. DebugLogger('Instead of ' + filename + ', using ' + realfilename +
  3129. ' from offset ' + IntToStr(Offset) + ', size ' + IntToStr(Size));
  3130. {$ENDIF}
  3131. end;
  3132. end;
  3133. {$IFDEF DXGETTEXTDEBUG}
  3134. DebugLogger('Reading .mo data from file ''' + filename + '''');
  3135. {$ENDIF}
  3136. // Find TMoFile object
  3137. MoFilesCS.BeginWrite;
  3138. try
  3139. idxname := realfilename + ' //\\ ' + IntToStr(Offset);
  3140. if MoFiles.Find(idxname, idx) then
  3141. begin
  3142. Result := MoFiles.Objects[idx] as TMoFile;
  3143. end
  3144. else
  3145. begin
  3146. Result := TMoFile.Create(realfilename, Offset, Size,
  3147. UseMemoryMappedFiles);
  3148. MoFiles.AddObject(idxname, Result);
  3149. end;
  3150. inc(Result.Users);
  3151. finally
  3152. MoFilesCS.EndWrite;
  3153. end;
  3154. end;
  3155. function TFileLocator.ReadInt64(str: TStream): int64;
  3156. begin
  3157. Assert(SizeOf(Result) = 8);
  3158. str.ReadBuffer(Result, 8);
  3159. end;
  3160. procedure TFileLocator.ReleaseMoFile(mofile: TMoFile);
  3161. var
  3162. i: Integer;
  3163. begin
  3164. Assert(mofile <> nil);
  3165. MoFilesCS.BeginWrite;
  3166. try
  3167. dec(mofile.Users);
  3168. if mofile.Users <= 0 then
  3169. begin
  3170. i := MoFiles.Count - 1;
  3171. while i >= 0 do
  3172. begin
  3173. if MoFiles.Objects[i] = mofile then
  3174. begin
  3175. MoFiles.delete(i);
  3176. FreeAndNil(mofile);
  3177. break;
  3178. end;
  3179. dec(i);
  3180. end;
  3181. end;
  3182. finally
  3183. MoFilesCS.EndWrite;
  3184. end;
  3185. end;
  3186. { TTP_Retranslator }
  3187. constructor TTP_Retranslator.Create;
  3188. begin
  3189. list := TList.Create;
  3190. end;
  3191. destructor TTP_Retranslator.Destroy;
  3192. var
  3193. i: Integer;
  3194. begin
  3195. for i := 0 to list.Count - 1 do
  3196. TObject(list.Items[i]).Free;
  3197. FreeAndNil(list);
  3198. inherited;
  3199. end;
  3200. procedure TTP_Retranslator.Execute;
  3201. var
  3202. i: Integer;
  3203. sl: TStrings;
  3204. item: TTP_RetranslatorItem;
  3205. newvalue: TranslatedUnicodeString;
  3206. comp: TGnuGettextComponentMarker;
  3207. ppi: PPropInfo;
  3208. begin
  3209. for i := 0 to list.Count - 1 do
  3210. begin
  3211. item := TObject(list.Items[i]) as TTP_RetranslatorItem;
  3212. if not Assigned(item.obj) then
  3213. continue; // JR 20223-04-18 to avoid protection faults
  3214. if item.obj is TComponent then
  3215. begin
  3216. comp := TComponent(item.obj).FindComponent('GNUgettextMarker')
  3217. as TGnuGettextComponentMarker;
  3218. if Assigned(comp) and (self <> comp.Retranslator) then
  3219. begin
  3220. comp.Retranslator.Execute;
  3221. continue;
  3222. end;
  3223. end;
  3224. if item.obj is TStrings then
  3225. begin
  3226. // Since we don't know the order of items in sl, and don't have
  3227. // the original .Objects[] anywhere, we cannot anticipate anything
  3228. // about the current sl.Strings[] and sl.Objects[] values. We therefore
  3229. // have to discard both values. We can, however, set the original .Strings[]
  3230. // value into the list and retranslate that.
  3231. sl := TStringList.Create;
  3232. try
  3233. sl.Text := item.OldValue;
  3234. Instance.TranslateStrings(sl, textdomain);
  3235. (item.obj as TStrings).BeginUpdate;
  3236. try
  3237. (item.obj as TStrings).Text := sl.Text;
  3238. finally
  3239. (item.obj as TStrings).EndUpdate;
  3240. end;
  3241. finally
  3242. FreeAndNil(sl);
  3243. end;
  3244. end
  3245. else
  3246. begin
  3247. if (textdomain = '') or (textdomain = DefaultTextDomain) then
  3248. newvalue := ComponentGettext(item.OldValue, Instance)
  3249. else
  3250. newvalue := Instance.dgettext(textdomain, item.OldValue);
  3251. ppi := GetPropInfo(item.obj, item.Propname);
  3252. if ppi <> nil then
  3253. begin
  3254. SetWideStrProp(item.obj, ppi, newvalue);
  3255. end
  3256. else
  3257. begin
  3258. {$IFDEF DXGETTEXTDEBUG}
  3259. Instance.DebugWriteln
  3260. ('ERROR: On retranslation, property disappeared: ' +
  3261. item.Propname + ' for object of type ' + item.obj.ClassName);
  3262. {$ENDIF}
  3263. end;
  3264. end;
  3265. end;
  3266. end;
  3267. procedure TTP_Retranslator.Remember(obj: TObject;
  3268. Propname: ComponentNameString; OldValue: TranslatedUnicodeString);
  3269. var
  3270. item: TTP_RetranslatorItem;
  3271. begin
  3272. item := TTP_RetranslatorItem.Create;
  3273. item.obj := obj;
  3274. item.Propname := Propname;
  3275. item.OldValue := OldValue;
  3276. list.Add(item);
  3277. end;
  3278. { TGnuGettextComponentMarker }
  3279. destructor TGnuGettextComponentMarker.Destroy;
  3280. begin
  3281. FreeAndNil(Retranslator);
  3282. inherited;
  3283. end;
  3284. { THook }
  3285. constructor THook.Create(OldProcedure, NewProcedure: pointer;
  3286. FollowJump: boolean = false);
  3287. { Idea and original code from Igor Siticov }
  3288. { Modified by Jacques Garcia Vazquez and Lars Dybdahl }
  3289. begin
  3290. {$IFNDEF CPU386}
  3291. {$IFNDEF CPUx64}
  3292. raise Exception.Create
  3293. ('This procedure only works on Intel i386 or x64 compatible processors.');
  3294. {$ENDIF}
  3295. {$ENDIF}
  3296. oldproc := OldProcedure;
  3297. newproc := NewProcedure;
  3298. Reset(FollowJump);
  3299. end;
  3300. destructor THook.Destroy;
  3301. begin
  3302. Shutdown;
  3303. inherited;
  3304. end;
  3305. procedure THook.Disable;
  3306. begin
  3307. Assert(PatchPosition <> nil,
  3308. 'Patch position in THook was nil when Disable was called');
  3309. PatchPosition[0] := Original[0];
  3310. PatchPosition[1] := Original[1];
  3311. PatchPosition[2] := Original[2];
  3312. PatchPosition[3] := Original[3];
  3313. PatchPosition[4] := Original[4];
  3314. end;
  3315. procedure THook.Enable;
  3316. begin
  3317. Assert(PatchPosition <> nil,
  3318. 'Patch position in THook was nil when Enable was called');
  3319. PatchPosition[0] := Patch[0];
  3320. PatchPosition[1] := Patch[1];
  3321. PatchPosition[2] := Patch[2];
  3322. PatchPosition[3] := Patch[3];
  3323. PatchPosition[4] := Patch[4];
  3324. end;
  3325. procedure THook.Reset(FollowJump: boolean);
  3326. var
  3327. Offset: Integer;
  3328. {$IFDEF LINUX}
  3329. p: pointer;
  3330. pagesize: Integer;
  3331. {$ENDIF}
  3332. {$IFDEF MSWindows}
  3333. ov: Cardinal;
  3334. {$ENDIF}
  3335. begin
  3336. if PatchPosition <> nil then
  3337. Shutdown;
  3338. PatchPosition := oldproc;
  3339. if FollowJump and (Word(oldproc^) = $25FF) then
  3340. begin
  3341. // This finds the correct procedure if a virtual jump has been inserted
  3342. // at the procedure address
  3343. inc(PatchPosition, 2); // skip the jump
  3344. PatchPosition := PAnsiChar(pointer(pointer(PatchPosition)^)^);
  3345. end;
  3346. Offset := Integer(newproc) - Integer(pointer(PatchPosition)) - 5;
  3347. Patch[0] := ansichar($E9);
  3348. Patch[1] := ansichar(Offset and 255);
  3349. Patch[2] := ansichar((Offset shr 8) and 255);
  3350. Patch[3] := ansichar((Offset shr 16) and 255);
  3351. Patch[4] := ansichar((Offset shr 24) and 255);
  3352. Original[0] := PatchPosition[0];
  3353. Original[1] := PatchPosition[1];
  3354. Original[2] := PatchPosition[2];
  3355. Original[3] := PatchPosition[3];
  3356. Original[4] := PatchPosition[4];
  3357. {$IFDEF MSWINDOWS}
  3358. if not VirtualProtect(pointer(PatchPosition), 5,
  3359. PAGE_EXECUTE_READWRITE, @ov) then
  3360. RaiseLastOSError;
  3361. {$ENDIF}
  3362. {$IFDEF LINUX}
  3363. pagesize := sysconf(_SC_PAGE_SIZE);
  3364. p := pointer(PatchPosition);
  3365. p := pointer((Integer(p) + pagesize - 1) and not(pagesize - 1) -
  3366. pagesize);
  3367. if mprotect(p, pagesize, PROT_READ + PROT_WRITE + PROT_EXEC) <> 0 then
  3368. RaiseLastOSError;
  3369. {$ENDIF}
  3370. end;
  3371. procedure THook.Shutdown;
  3372. begin
  3373. Disable;
  3374. PatchPosition := nil;
  3375. end;
  3376. procedure HookIntoResourceStrings(enabled: boolean = True;
  3377. SupportPackages: boolean = false);
  3378. begin
  3379. HookLoadResString.Reset(SupportPackages);
  3380. HookLoadStr.Reset(SupportPackages);
  3381. HookFmtLoadStr.Reset(SupportPackages);
  3382. if enabled then
  3383. begin
  3384. HookLoadResString.Enable;
  3385. HookLoadStr.Enable;
  3386. HookFmtLoadStr.Enable;
  3387. end;
  3388. end;
  3389. { TMoFile }
  3390. function TMoFile.autoswap32(i: Cardinal): Cardinal;
  3391. var
  3392. cnv1, cnv2: record case Integer of 0: (arr: array [0 .. 3] of byte);
  3393. 1: (int: Cardinal);
  3394. end;
  3395. begin
  3396. if doswap then
  3397. begin
  3398. cnv1.int := i;
  3399. cnv2.arr[0] := cnv1.arr[3];
  3400. cnv2.arr[1] := cnv1.arr[2];
  3401. cnv2.arr[2] := cnv1.arr[1];
  3402. cnv2.arr[3] := cnv1.arr[0];
  3403. Result := cnv2.int;
  3404. end
  3405. else
  3406. Result := i;
  3407. end;
  3408. function TMoFile.CardinalInMem(baseptr: PAnsiChar; Offset: Cardinal)
  3409. : Cardinal;
  3410. var
  3411. pc: ^Cardinal;
  3412. begin
  3413. inc(baseptr, Offset);
  3414. pc := pointer(baseptr);
  3415. Result := pc^;
  3416. if doswap then
  3417. autoswap32(Result);
  3418. end;
  3419. constructor TMoFile.Create(const filename: FilenameString;
  3420. const Offset: int64; Size: int64; const xUseMemoryMappedFiles: boolean);
  3421. var
  3422. i: Cardinal;
  3423. nn: Integer;
  3424. mofile: TFileStream;
  3425. begin
  3426. if SizeOf(i) <> 4 then
  3427. raise EGGProgrammingError.Create
  3428. ('TDomain in gnugettext is written for an architecture that has 32 bit integers.');
  3429. {$IFDEF mswindows}
  3430. FUseMemoryMappedFiles := xUseMemoryMappedFiles;
  3431. {$ENDIF}
  3432. {$IFDEF linux}
  3433. FUseMemoryMappedFiles := false;
  3434. {$ENDIF}
  3435. if FUseMemoryMappedFiles then
  3436. begin
  3437. // Map the mo file into memory and let the operating system decide how to cache
  3438. mo := createfile(PChar(filename), GENERIC_READ, FILE_SHARE_READ, nil,
  3439. OPEN_EXISTING, 0, 0);
  3440. if mo = INVALID_HANDLE_VALUE then
  3441. raise EGGIOError.Create('Cannot open file ' + filename);
  3442. momapping := CreateFileMapping(mo, nil, PAGE_READONLY, 0, 0, nil);
  3443. if momapping = 0 then
  3444. raise EGGIOError.Create('Cannot create memory map on file ' + filename);
  3445. momemoryHandle := MapViewOfFile(momapping, FILE_MAP_READ, 0, 0, 0);
  3446. if momemoryHandle = nil then
  3447. begin
  3448. raise EGGIOError.Create('Cannot map file ' + filename +
  3449. ' into memory. Reason: ' + GetLastWinError);
  3450. end;
  3451. momemory := momemoryHandle + Offset;
  3452. end
  3453. else
  3454. begin
  3455. // Read the whole file into memory
  3456. mofile := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone);
  3457. try
  3458. if (Size = 0) then
  3459. Size := mofile.Size;
  3460. Getmem(momemoryHandle, Size);
  3461. momemory := momemoryHandle;
  3462. mofile.Seek(Offset, soFromBeginning);
  3463. mofile.ReadBuffer(momemory^, Size);
  3464. finally
  3465. FreeAndNil(mofile);
  3466. end;
  3467. end;
  3468. // Check the magic number
  3469. doswap := false;
  3470. i := CardinalInMem(momemory, 0);
  3471. if (i <> $950412DE) and (i <> $DE120495) then
  3472. raise EGGIOError.Create('This file is not a valid GNU gettext mo file: ' +
  3473. filename);
  3474. doswap := (i = $DE120495);
  3475. // Find the positions in the file according to the file format spec
  3476. CardinalInMem(momemory, 4);
  3477. // Read the version number, but don't use it for anything.
  3478. N := CardinalInMem(momemory, 8); // Get string count
  3479. O := CardinalInMem(momemory, 12); // Get offset of original strings
  3480. T := CardinalInMem(momemory, 16); // Get offset of translated strings
  3481. // Calculate start conditions for a binary search
  3482. nn := N;
  3483. startindex := 1;
  3484. while nn <> 0 do
  3485. begin
  3486. nn := nn shr 1;
  3487. startindex := startindex shl 1;
  3488. end;
  3489. startindex := startindex shr 1;
  3490. startstep := startindex shr 1;
  3491. end;
  3492. destructor TMoFile.Destroy;
  3493. begin
  3494. if FUseMemoryMappedFiles then
  3495. begin
  3496. UnMapViewOfFile(momemoryHandle);
  3497. try
  3498. CloseHandle(momapping);
  3499. except
  3500. end;
  3501. try
  3502. CloseHandle(mo);
  3503. except
  3504. end;
  3505. end
  3506. else
  3507. begin
  3508. FreeMem(momemoryHandle);
  3509. end;
  3510. inherited;
  3511. end;
  3512. function TMoFile.gettext(const msgid: RawUtf8String; var found: boolean)
  3513. : RawUtf8String;
  3514. var
  3515. i, step: Cardinal;
  3516. Offset, pos: Cardinal;
  3517. CompareResult: Integer;
  3518. msgidptr, a, b: PAnsiChar;
  3519. abidx: Integer;
  3520. Size, msgidsize: Integer;
  3521. begin
  3522. found := false;
  3523. msgidptr := PAnsiChar(msgid);
  3524. msgidsize := length(msgid);
  3525. // Do binary search
  3526. i := startindex;
  3527. step := startstep;
  3528. while True do
  3529. begin
  3530. // Get string for index i
  3531. pos := O + 8 * (i - 1);
  3532. Offset := CardinalInMem(momemory, pos + 4);
  3533. Size := CardinalInMem(momemory, pos);
  3534. a := msgidptr;
  3535. b := momemory + Offset;
  3536. abidx := Size;
  3537. if msgidsize < abidx then
  3538. abidx := msgidsize;
  3539. CompareResult := 0;
  3540. while abidx <> 0 do
  3541. begin
  3542. CompareResult := Integer(byte(a^)) - Integer(byte(b^));
  3543. if CompareResult <> 0 then
  3544. break;
  3545. dec(abidx);
  3546. inc(a);
  3547. inc(b);
  3548. end;
  3549. if CompareResult = 0 then
  3550. CompareResult := msgidsize - Size;
  3551. if CompareResult = 0 then
  3552. begin // msgid=s
  3553. // Found the msgid
  3554. pos := T + 8 * (i - 1);
  3555. Offset := CardinalInMem(momemory, pos + 4);
  3556. Size := CardinalInMem(momemory, pos);
  3557. SetString(Result, momemory + Offset, Size);
  3558. found := True;
  3559. break;
  3560. end;
  3561. if step = 0 then
  3562. begin
  3563. // Not found
  3564. Result := msgid;
  3565. break;
  3566. end;
  3567. if CompareResult < 0 then
  3568. begin // msgid<s
  3569. if i < 1 + step then
  3570. i := 1
  3571. else
  3572. i := i - step;
  3573. step := step shr 1;
  3574. end
  3575. else
  3576. begin // msgid>s
  3577. i := i + step;
  3578. if i > N then
  3579. i := N;
  3580. step := step shr 1;
  3581. end;
  3582. end;
  3583. end;
  3584. var
  3585. param0: string;
  3586. initialization
  3587. {$IFDEF DXGETTEXTDEBUG}
  3588. {$IFDEF MSWINDOWS}
  3589. MessageBox(0,
  3590. 'gnugettext.pas debugging is enabled. Turn it off before releasing this piece of software.',
  3591. 'Information', MB_OK);
  3592. {$ENDIF}
  3593. {$IFDEF LINUX}
  3594. writeln(stderr,
  3595. 'gnugettext.pas debugging is enabled. Turn it off before releasing this piece of software.');
  3596. {$ENDIF}
  3597. {$ENDIF}
  3598. {$IFDEF FPC}
  3599. {$IFDEF LINUX}
  3600. SetLocale(LC_ALL, '');
  3601. SetCWidestringManager;
  3602. {$ENDIF LINUX}
  3603. {$ENDIF FPC}
  3604. // Get DLL/shared object filename
  3605. SetLength(ExecutableFilename, 300); // MAX_PATH ?
  3606. {$IFDEF MSWINDOWS}
  3607. SetLength(ExecutableFilename, GetModuleFileName(HInstance,
  3608. PChar(ExecutableFilename), length(ExecutableFilename)));
  3609. {$ENDIF}
  3610. {$IFDEF LINUX}
  3611. if ModuleIsLib or ModuleIsPackage then
  3612. begin
  3613. // This line has not been tested on Linux, yet, but should work.
  3614. SetLength(ExecutableFilename, GetModuleFileName(0, PChar(ExecutableFilename),
  3615. length(ExecutableFilename)));
  3616. end
  3617. else
  3618. ExecutableFilename := Paramstr(0);
  3619. {$ENDIF}
  3620. FileLocator := TFileLocator.Create;
  3621. FileLocator.Analyze;
  3622. ResourceStringDomainList := TStringList.Create;
  3623. ResourceStringDomainList.Add(DefaultTextDomain);
  3624. ResourceStringDomainListCS := TMultiReadExclusiveWriteSynchronizer.Create;
  3625. ComponentDomainList := TStringList.Create;
  3626. ComponentDomainList.Add(DefaultTextDomain);
  3627. ComponentDomainListCS := TMultiReadExclusiveWriteSynchronizer.Create;
  3628. DefaultInstance := TGnuGettextInstance.Create;
  3629. {$IFDEF MSWINDOWS}
  3630. Win32PlatformIsUnicode := (Win32Platform = VER_PLATFORM_WIN32_NT);
  3631. {$ENDIF}
  3632. // replace Borlands LoadResString with gettext enabled version:
  3633. {$IFDEF UNICODE}
  3634. HookLoadResString := THook.Create(@System.LoadResString, @LoadResStringW);
  3635. {$ELSE}
  3636. HookLoadResString := THook.Create(@System.LoadResString, @LoadResStringA);
  3637. {$ENDIF}
  3638. HookLoadStr := THook.Create(@System.SysUtils.LoadStr, @SysUtilsLoadStr);
  3639. HookFmtLoadStr := THook.Create(@System.SysUtils.FmtLoadStr,
  3640. @SysUtilsFmtLoadStr);
  3641. param0 := lowercase(extractfilename(Paramstr(0)));
  3642. if (param0 <> 'delphi32.exe') and (param0 <> 'kylix') and (param0 <> 'bds.exe')
  3643. then
  3644. HookIntoResourceStrings(AutoCreateHooks, false);
  3645. param0 := '';
  3646. finalization
  3647. FreeAndNil(DefaultInstance);
  3648. FreeAndNil(ResourceStringDomainListCS);
  3649. FreeAndNil(ResourceStringDomainList);
  3650. FreeAndNil(ComponentDomainListCS);
  3651. FreeAndNil(ComponentDomainList);
  3652. FreeAndNil(HookFmtLoadStr);
  3653. FreeAndNil(HookLoadStr);
  3654. FreeAndNil(HookLoadResString);
  3655. FreeAndNil(FileLocator);
  3656. end.