gnugettext.pas 151 KB

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