2
0

gnuGettext.pas 130 KB

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