sysutils.pas 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029
  1. {
  2. This file is part of the Pas2JS run time library.
  3. Copyright (c) 2017 by Mattias Gaertner
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. unit SysUtils;
  11. {$mode objfpc}
  12. interface
  13. uses
  14. RTLConsts, js;
  15. procedure FreeAndNil(var Obj);
  16. type
  17. TProcedure = procedure;
  18. {*****************************************************************************
  19. Various types
  20. *****************************************************************************}
  21. type
  22. { TFloatRec }
  23. TFloatRec = Record
  24. Exponent: Integer;
  25. Negative: Boolean;
  26. Digits: Array Of Char;
  27. End;
  28. TEndian = (Little,Big);
  29. TFileName = String;
  30. TByteArray = array [0..32767] of Byte;
  31. TWordArray = array [0..16383] of Word;
  32. TBytes = Array of byte;
  33. TStringArray = array of string;
  34. TMonthNameArray = array [1..12] of string;
  35. TDayTable = array [1..12] of Word;
  36. TWeekNameArray = array [1..7] of string;
  37. TMonthNames = TMonthNameArray;
  38. TDayNames = array[0..6] of string;
  39. {*****************************************************************************
  40. Exception handling
  41. *****************************************************************************}
  42. { Exception }
  43. Exception = class(TObject)
  44. private
  45. fMessage: String;
  46. fHelpContext: Integer;
  47. public
  48. constructor Create(const Msg: String); reintroduce;
  49. constructor CreateFmt(const Msg: string; const Args: array of jsvalue);
  50. constructor CreateHelp(const Msg: String; AHelpContext: Integer);
  51. constructor CreateFmtHelp(const Msg: string; const Args: array of jsvalue; AHelpContext: Integer);
  52. function ToString: String; override;
  53. property HelpContext: Integer read fHelpContext write fHelpContext;
  54. property Message: String read fMessage write fMessage;
  55. end;
  56. ExceptClass = class of Exception;
  57. EExternal = class(Exception);
  58. { General math errors }
  59. EMathError = class(EExternal);
  60. EInvalidOp = class(EMathError);
  61. EZeroDivide = class(EMathError);
  62. EOverflow = class(EMathError);
  63. EUnderflow = class(EMathError);
  64. EAbort = class(Exception);
  65. EInvalidCast = class(Exception);
  66. EAssertionFailed = class(Exception);
  67. EObjectCheck = class(Exception);
  68. { String conversion errors }
  69. EConvertError = class(Exception);
  70. EFormatError = class(Exception);
  71. { integer math exceptions }
  72. EIntError = Class(EExternal);
  73. EDivByZero = Class(EIntError);
  74. ERangeError = Class(EIntError);
  75. EIntOverflow = Class(EIntError);
  76. { General math errors }
  77. { Run-time and I/O Errors }
  78. EInOutError = class(Exception)
  79. public
  80. ErrorCode : Integer;
  81. end;
  82. EHeapMemoryError = class(Exception);
  83. EHeapException = EHeapMemoryError;
  84. EExternalException = class(EExternal);
  85. EInvalidPointer = Class(EHeapMemoryError);
  86. EOutOfMemory = Class(EHeapMemoryError);
  87. { EVariantError }
  88. EVariantError = Class(Exception)
  89. ErrCode : longint;
  90. Constructor CreateCode(Code : Longint);
  91. end;
  92. EAccessViolation = Class(EExternal);
  93. EBusError = Class(EAccessViolation);
  94. EPrivilege = class(EExternal);
  95. EStackOverflow = class(EExternal);
  96. EControlC = class(EExternal);
  97. { String conversion errors }
  98. { Other errors }
  99. EAbstractError = Class(Exception);
  100. EPropReadOnly = class(Exception);
  101. EPropWriteOnly = class(Exception);
  102. EIntfCastError = class(Exception);
  103. EInvalidContainer = class(Exception);
  104. EInvalidInsert = class(Exception);
  105. EPackageError = class(Exception);
  106. EOSError = class(Exception)
  107. public
  108. ErrorCode: Longint;
  109. end;
  110. ESafecallException = class(Exception);
  111. ENoThreadSupport = Class(Exception);
  112. ENoWideStringSupport = Class(Exception);
  113. ENotImplemented = class(Exception);
  114. EArgumentException = class(Exception);
  115. EArgumentOutOfRangeException = class(EArgumentException);
  116. EArgumentNilException = class(EArgumentException);
  117. EPathTooLongException = class(Exception);
  118. ENotSupportedException = class(Exception);
  119. EDirectoryNotFoundException = class(Exception);
  120. EFileNotFoundException = class(Exception);
  121. EPathNotFoundException = class(Exception);
  122. ENoConstructException = class(Exception);
  123. //function GetTickCount: Integer;
  124. {*****************************************************************************
  125. String function
  126. *****************************************************************************}
  127. Const
  128. EmptyStr = '';
  129. EmptyWideStr = ''; // No difference here.
  130. HexDisplayPrefix: string = '$';
  131. LeadBytes = [] unimplemented;
  132. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  133. function LeftStr(const S: string; Count: Integer): String; assembler;
  134. function RightStr(const S: string; Count: Integer): String; assembler;
  135. function Trim(const S: String): String; assembler;
  136. function TrimLeft(const S: String): String; assembler;
  137. function TrimRight(const S: String): String; assembler;
  138. function UpperCase(const s: String): String; assembler; overload;
  139. function LowerCase(const s: String): String; assembler; overload;
  140. function CompareStr(const s1, s2: String): Integer; assembler;
  141. function SameStr(const s1, s2: String): Boolean; assembler;
  142. function CompareText(const s1, s2: String): Integer; assembler;
  143. function SameText(const s1, s2: String): Boolean; assembler;
  144. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  145. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  146. function AnsiCompareStr(const s1, s2: String): Integer;
  147. procedure AppendStr(var Dest: String; const S: string);
  148. function Format(const Fmt: String; const Args: array of JSValue): String;
  149. // JavaScript built-in functions
  150. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler; overload;
  151. function NormalizeStr(const S: String; const Norm: String = 'NFC'): String; assembler; overload; // not in IE
  152. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  153. Type
  154. TStringReplaceFlag = (rfReplaceAll, rfIgnoreCase);
  155. TReplaceFlag = TStringReplaceFlag;
  156. TStringReplaceFlags = set of TStringReplaceFlag;
  157. TReplaceFlags = TStringReplaceFlags;
  158. function StringReplace(aOriginal, aSearch, aReplace : string; Flags : TStringReplaceFlags) : String;
  159. function QuoteString(aOriginal : String; AQuote : Char) : String;
  160. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  161. function AdjustLineBreaks(const S: string): string;
  162. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  163. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  164. function WrapText(const Line: string; MaxCol: Integer): string;
  165. { *****************************************************************************
  166. Integer conversions
  167. *****************************************************************************}
  168. function IntToStr(const Value: Integer): string;
  169. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  170. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  171. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  172. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  173. Function StrToInt(const S : String) : Integer;
  174. Function StrToNativeInt(const S : String) : NativeInt;
  175. // For compatibility
  176. Function StrToInt64(const S : String) : NativeLargeInt;
  177. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  178. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  179. Function StrToQWord(const S : String) : NativeLargeUInt;
  180. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  181. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  182. Function StrToUInt64(const S : String) : NativeLargeUInt;
  183. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  184. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  185. Function StrToDWord(const S : String) : DWord;
  186. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  187. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  188. function IntToHex(Value: NativeInt; Digits: integer): string;
  189. { *****************************************************************************
  190. Float conversions
  191. *****************************************************************************}
  192. const
  193. // Note: Currency is internally a double, multiplied by 10000 and truncated.
  194. // The below values are the safe limits, within every step exists.
  195. // Since currency is a double it can take much larger values, but the result
  196. // may differ from Delphi/FPC
  197. MaxCurrency: Currency = 450359962737.0495; // fpc: 922337203685477.5807;
  198. MinCurrency: Currency = -450359962737.0496; // fpc: -922337203685477.5808;
  199. Type
  200. TFloatFormat = (ffFixed,ffGeneral,ffExponent,ffNumber,ffCurrency);
  201. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  202. Function FloatToStr(Value: Double): String;
  203. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  204. Function TryStrToFloat(const S : String; Out res : Double) : Boolean;
  205. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  206. Function StrToFloat(const S : String) : Double;
  207. Function FormatFloat (Fmt : String; aValue : Double) : String;
  208. { *****************************************************************************
  209. Boolean conversions
  210. *****************************************************************************}
  211. Var
  212. TrueBoolStrs, FalseBoolStrs : Array of String;
  213. function StrToBool(const S: String): Boolean;
  214. function BoolToStr(B: Boolean; UseBoolStrs:Boolean=False): string;
  215. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  216. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  217. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  218. {*****************************************************************************
  219. OS/Environment
  220. *****************************************************************************}
  221. Const
  222. ConfigExtension : String = '.cfg';
  223. SysConfigDir : String = '';
  224. type
  225. TOnGetEnvironmentVariable = function(Const EnvVar: String): String;
  226. TOnGetEnvironmentString = function(Index: Integer): String;
  227. TOnGetEnvironmentVariableCount = function: Integer;
  228. var
  229. OnGetEnvironmentVariable: TOnGetEnvironmentVariable;
  230. OnGetEnvironmentString: TOnGetEnvironmentString;
  231. OnGetEnvironmentVariableCount: TOnGetEnvironmentVariableCount;
  232. function GetEnvironmentVariable(Const EnvVar: String): String;
  233. function GetEnvironmentVariableCount: Integer;
  234. function GetEnvironmentString(Index: Integer): String;
  235. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  236. Procedure Abort;
  237. {*****************************************************************************
  238. Events
  239. *****************************************************************************}
  240. Type
  241. TEventType = (etCustom,etInfo,etWarning,etError,etDebug);
  242. TEventTypes = Set of TEventType;
  243. {*****************************************************************************
  244. Date and time
  245. *****************************************************************************}
  246. Type
  247. TDateTime = type double;
  248. TTime = type TDateTime;
  249. TDate = type TDateTime;
  250. TSystemTime = record
  251. Year, Month, Day, DayOfWeek: word;
  252. Hour, Minute, Second, MilliSecond: word;
  253. end ;
  254. TTimeStamp = record
  255. Time: longint; { Number of milliseconds since midnight }
  256. Date: longint; { One plus number of days since 1/1/0001 }
  257. end ;
  258. Var
  259. TimeSeparator : char = ':';
  260. DateSeparator : char = '-';
  261. ShortDateFormat : string = 'yyyy-mm-dd';
  262. LongDateFormat : string = 'ddd, yyyy-mm-dd';
  263. ShortTimeFormat : string = 'hh:nn';
  264. LongTimeFormat : string = 'hh:nn:ss';
  265. DecimalSeparator : string = '.';
  266. ThousandSeparator : string;
  267. TimeAMString : string = 'AM';
  268. TimePMString : string = 'PM';
  269. const
  270. HoursPerDay = 24;
  271. MinsPerHour = 60;
  272. SecsPerMin = 60;
  273. MSecsPerSec = 1000;
  274. MinsPerDay = HoursPerDay * MinsPerHour;
  275. SecsPerDay = MinsPerDay * SecsPerMin;
  276. MSecsPerDay = SecsPerDay * MSecsPerSec;
  277. MaxDateTime: TDateTime = 2958465.99999999;
  278. MinDateTime: TDateTime = -693593.99999999;
  279. JulianEpoch = TDateTime(-2415018.5);
  280. UnixEpoch = JulianEpoch + TDateTime(2440587.5);
  281. DateDelta = 693594; // Days between 1/1/0001 and 12/31/1899
  282. UnixDateDelta = 25569;
  283. { True=Leapyear }
  284. Var
  285. MonthDays : array [Boolean] of TDayTable =
  286. ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
  287. (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
  288. ShortMonthNames : TMonthNames = (
  289. 'Jan',
  290. 'Feb',
  291. 'Mar',
  292. 'Apr',
  293. 'May',
  294. 'Jun',
  295. 'Jul',
  296. 'Aug',
  297. 'Sep',
  298. 'Oct',
  299. 'Nov',
  300. 'Dec');
  301. LongMonthNames : TMonthNames = (
  302. 'January',
  303. 'February',
  304. 'March',
  305. 'April',
  306. 'May',
  307. 'June',
  308. 'July',
  309. 'August',
  310. 'September',
  311. 'October',
  312. 'November',
  313. 'December');
  314. ShortDayNames : TDayNames = (
  315. 'Sun',
  316. 'Mon',
  317. 'Tue',
  318. 'Wed',
  319. 'Thu',
  320. 'Fri',
  321. 'Sat');
  322. LongDayNames : TDayNames = (
  323. 'Sunday',
  324. 'Monday',
  325. 'Tuesday',
  326. 'Wednesday',
  327. 'Thursday',
  328. 'Friday',
  329. 'Saturday');
  330. type
  331. // Stub, for easier porting of FPC/Delphi code.
  332. // Reading/Writing the properties will actually set the global variables
  333. { TFormatSettings }
  334. TFormatSettings = class(TObject)
  335. private
  336. function GetCurrencyDecimals: Byte;
  337. function GetCurrencyFormat: Byte;
  338. function GetCurrencyString: String;
  339. function GetDateSeparator: char;
  340. function GetDecimalSeparator: string;
  341. function GetLongDateFormat: string;
  342. function GetLongDayNames: TDayNames;
  343. function GetLongMonthNames: TMonthNames;
  344. function GetLongTimeFormat: string;
  345. function GetNegCurrFormat: Byte;
  346. function GetShortDateFormat: string;
  347. function GetShortDayNames: TDayNames;
  348. function GetShortMonthNames: TMonthNames;
  349. function GetShortTimeFormat: string;
  350. function GetThousandSeparator: string;
  351. function GetTimeAMString: string;
  352. function GetTimePMString: string;
  353. function GetTimeSeparator: char;
  354. procedure SetCurrencyFormat(AValue: Byte);
  355. procedure SetCurrencyString(AValue: String);
  356. procedure SetDateSeparator(const Value: char);
  357. procedure SetDecimalSeparator(const Value: string);
  358. procedure SetLongDateFormat(const Value: string);
  359. procedure SetLongDayNames(AValue: TDayNames);
  360. procedure SetLongMonthNames(AValue: TMonthNames);
  361. procedure SetLongTimeFormat(const Value: string);
  362. procedure SetNegCurrFormat(AValue: Byte);
  363. procedure SetShortDateFormat(const Value: string);
  364. procedure SetShortDayNames(AValue: TDayNames);
  365. procedure SetShortMonthNames(AValue: TMonthNames);
  366. procedure SetShortTimeFormat(const Value: string);
  367. procedure SetCurrencyDecimals(AValue: Byte);
  368. procedure SetThousandSeparator(const Value: string);
  369. procedure SetTimeAMString(const Value: string);
  370. procedure SetTimePMString(const Value: string);
  371. procedure SetTimeSeparator(const Value: char);
  372. public
  373. Property ShortMonthNames : TMonthNames Read GetShortMonthNames Write SetShortMonthNames;
  374. Property LongMonthNames : TMonthNames Read GetLongMonthNames Write SetLongMonthNames;
  375. Property ShortDayNames : TDayNames Read GetShortDayNames Write SetShortDayNames;
  376. Property LongDayNames : TDayNames Read GetLongDayNames Write SetLongDayNames;
  377. property TimeSeparator : char read GetTimeSeparator write SetTimeSeparator;
  378. property DateSeparator : char read GetDateSeparator write SetDateSeparator;
  379. property ShortDateFormat : string read GetShortDateFormat write SetShortDateFormat;
  380. property LongDateFormat : string read GetLongDateFormat write SetLongDateFormat;
  381. property ShortTimeFormat : string read GetShortTimeFormat write SetShortTimeFormat;
  382. property LongTimeFormat : string read GetLongTimeFormat write SetLongTimeFormat;
  383. property DecimalSeparator : string read GetDecimalSeparator write SetDecimalSeparator;
  384. property ThousandSeparator : string read GetThousandSeparator write SetThousandSeparator;
  385. property TimeAMString : string read GetTimeAMString write SetTimeAMString;
  386. property TimePMString : string read GetTimePMString write SetTimePMString;
  387. Property CurrencyFormat : Byte read GetCurrencyFormat Write SetCurrencyFormat;
  388. Property NegCurrFormat : Byte read GetNegCurrFormat Write SetNegCurrFormat;
  389. Property CurrencyDecimals : Byte Read GetCurrencyDecimals Write SetCurrencyDecimals;
  390. Property CurrencyString : String Read GetCurrencyString Write SetCurrencyString;
  391. end;
  392. Var
  393. FormatSettings: TFormatSettings;
  394. TwoDigitYearCenturyWindow : word = 50;
  395. { Threshold to be subtracted from year before age-detection.}
  396. function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  397. function JSDateToDateTime(aDate : TJSDate) : TDateTime;
  398. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  399. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  400. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  401. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  402. function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
  403. function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
  404. function EncodeDate(Year, Month, Day :word): TDateTime;
  405. function EncodeTime(Hour, Minute, Second, MilliSecond:word): TDateTime;
  406. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  407. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  408. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  409. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  410. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  411. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  412. function DayOfWeek(DateTime: TDateTime): integer;
  413. function Date: TDateTime;
  414. function Time: TDateTime;
  415. function Now: TDateTime;
  416. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  417. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  418. function IsLeapYear(Year: Word): boolean;
  419. function DateToStr(Date: TDateTime): string;
  420. // function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings): string;
  421. function TimeToStr(Time: TDateTime): string;
  422. // function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings): string;
  423. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  424. // function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings; ForceTimeIfZero : Boolean = False): string;
  425. function StrToDate(const S: String): TDateTime;
  426. function StrToDate(const S: String; separator : char): TDateTime;
  427. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  428. //function StrToDate(const S: string; FormatSettings : TFormatSettings): TDateTime;
  429. function StrToTime(const S: String): TDateTime;
  430. function StrToTime(const S: String; separator : char): TDateTime;
  431. // function StrToTime(const S: string; FormatSettings : TFormatSettings): TDateTime;
  432. function StrToDateTime(const S: String): TDateTime;
  433. //function StrToDateTime(const s: ShortString; const FormatSettings : TFormatSettings): TDateTime;
  434. function FormatDateTime(const FormatStr: string; const DateTime: TDateTime): string;
  435. // function FormatDateTime(const FormatStr: string; DateTime: TDateTime; const FormatSettings: TFormatSettings; Options : TFormatDateTimeOptions = []): string;
  436. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  437. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  438. function TryStrToDate(const S: String; out Value: TDateTime; const useformat : string; separator : char): Boolean;
  439. // function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  440. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  441. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  442. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  443. // function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  444. // function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  445. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  446. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  447. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  448. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  449. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  450. function CurrentYear:Word;
  451. procedure ReplaceTime(var dati: TDateTime; NewTime : TDateTime);
  452. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  453. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  454. { *****************************************************************************
  455. Currency support
  456. *****************************************************************************}
  457. Var
  458. CurrencyFormat : Byte = 0;
  459. NegCurrFormat : Byte = 0;
  460. CurrencyDecimals : Byte = 2;
  461. CurrencyString : String = '$';
  462. Function FloattoCurr (Const Value : Extended) : Currency;
  463. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  464. Function CurrToStr(Value: Currency): string;
  465. //Function CurrToStr(Value: Currency; Const FormatSettings: TFormatSettings): string;
  466. function StrToCurr(const S: string): Currency;
  467. //function StrToCurr(const S: string; Const FormatSettings: TFormatSettings): Currency;
  468. function TryStrToCurr(const S: string;Out Value : Currency): Boolean;
  469. //function TryStrToCurr(const S: string;Out Value : Currency; Const FormatSettings: TFormatSettings): Boolean;
  470. function StrToCurrDef(const S: string; Default : Currency): Currency;
  471. //function StrToCurrDef(const S: string; Default : Currency; Const FormatSettings: TFormatSettings): Currency;
  472. {*****************************************************************************
  473. File Paths
  474. *****************************************************************************}
  475. type
  476. PathStr = String;
  477. //function ExtractFilePath(const FileName: PathStr): PathStr;
  478. {*****************************************************************************
  479. Interfaces
  480. *****************************************************************************}
  481. const
  482. GUID_NULL: TGuid = '{00000000-0000-0000-0000-000000000000}';
  483. function Supports(const Instance: IInterface; const AClass: TClass; out Obj): Boolean; overload;
  484. function Supports(const Instance: IInterface; const IID: TGuid; out Intf): Boolean; overload;
  485. function Supports(const Instance: TObject; const IID: TGuid; out Intf): Boolean; overload;
  486. function Supports(const Instance: TObject; const IID: TGuidString; out Intf): Boolean; overload;
  487. function Supports(const Instance: IInterface; const AClass: TClass): Boolean; overload;
  488. function Supports(const Instance: IInterface; const IID: TGuid): Boolean; overload;
  489. function Supports(const Instance: TObject; const IID: TGuid): Boolean; overload;
  490. function Supports(const Instance: TObject; const IID: TGuidString): Boolean; overload;
  491. function Supports(const AClass: TClass; const IID: TGuid): Boolean; overload;
  492. function Supports(const AClass: TClass; const IID: TGuidString): Boolean; overload;
  493. function TryStringToGUID(const s: string; out Guid: TGuid): Boolean;
  494. function StringToGUID(const S: string): TGuid;
  495. function GUIDToString(const guid: TGuid): string;
  496. function IsEqualGUID(const guid1, guid2: TGuid): Boolean;
  497. function GuidCase(const guid: TGuid; const List: array of TGuid): Integer;
  498. implementation
  499. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  500. Var
  501. S : String;
  502. begin
  503. S:='Application raised an exception '+ExceptObject.ClassName;
  504. if ExceptObject is Exception then
  505. S:=S+' : '+Exception(ExceptObject).Message;
  506. {$IFDEF BROWSER}
  507. asm
  508. window.alert(S);
  509. end;
  510. {$ENDIF}
  511. {$IFDEF NODEJS}
  512. Writeln(S);
  513. {$ENDIF}
  514. if ExceptAddr=nil then;
  515. end;
  516. Const
  517. SAbortError = 'Operation aborted';
  518. procedure Abort;
  519. begin
  520. Raise EAbort.Create(SAbortError);
  521. end;
  522. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  523. Var
  524. I : integer;
  525. begin
  526. Result:=False;
  527. I:=Length(CSet)-1;
  528. While (Not Result) and (I>=0) do
  529. begin
  530. Result:=(Ch=CSet[i]);
  531. Dec(I);
  532. end;
  533. end;
  534. function LeftStr(const S: string; Count: Integer): String; assembler;
  535. asm
  536. return (Count>0) ? S.substr(0,Count) : "";
  537. end;
  538. function RightStr(const S: string; Count: Integer): String; assembler;
  539. asm
  540. var l = S.length;
  541. return (Count<1) ? "" : ( Count>=l ? S : S.substr(l-Count));
  542. end;
  543. function Trim(const S: String): String; assembler;
  544. asm
  545. return S.trim();
  546. end;
  547. function TrimLeft(const S: String): String; assembler;
  548. asm
  549. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'');
  550. end;
  551. function TrimRight(const S: String): String; assembler;
  552. asm
  553. return S.replace(/[\s\uFEFF\xA0\x00-\x1f]+$/,'');
  554. end;
  555. function IntToStr(const Value: Integer): string;
  556. begin
  557. Result:=str(Value);
  558. end;
  559. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  560. Const
  561. Rounds = '234567890';
  562. var
  563. Buffer: String; //Though str func returns only 25 chars, this might change in the future
  564. InfNan: string;
  565. Error, N, L, Start, C: Integer;
  566. GotNonZeroBeforeDot, BeforeDot : boolean;
  567. begin
  568. if Value=0 then ;
  569. SetLength(Result.Digits,19);
  570. asm
  571. Buffer=Value.toPrecision(21); // Double precision
  572. end;
  573. N := 1;
  574. L := Length(Buffer);
  575. while Buffer[N]=' ' do
  576. Inc(N);
  577. Result.Negative := (Buffer[N] = '-');
  578. if Result.Negative then
  579. Inc(N)
  580. else if (Buffer[N] = '+') then
  581. inc(N);
  582. { special cases for Inf and Nan }
  583. if (L>=N+2) then
  584. begin
  585. InfNan:=copy(Buffer,N,3);
  586. if (InfNan='Inf') then
  587. begin
  588. Result.Digits[0]:=#0;
  589. Result.Exponent:=32767;
  590. exit
  591. end;
  592. if (InfNan='Nan') then
  593. begin
  594. Result.Digits[0]:=#0;
  595. Result.Exponent:=-32768;
  596. exit
  597. end;
  598. end;
  599. Start := N; //Start of digits
  600. Result.Exponent := 0; BeforeDot := true;
  601. GotNonZeroBeforeDot := false;
  602. while (L>=N) and (Buffer[N]<>'E') do
  603. begin
  604. if Buffer[N]='.' then
  605. BeforeDot := false
  606. else
  607. begin
  608. if BeforeDot then
  609. begin // Currently this is always 1 char
  610. Inc(Result.Exponent);
  611. Result.Digits[N-Start] := Buffer[N];
  612. if Buffer[N] <> '0' then
  613. GotNonZeroBeforeDot := true;
  614. end
  615. else
  616. Result.Digits[N-Start-1] := Buffer[N]
  617. end;
  618. Inc(N);
  619. end;
  620. Inc(N); // Pass through 'E'
  621. if N<=L then
  622. begin
  623. Val(Copy(Buffer, N, L-N+1), C, Error); // Get exponent after 'E'
  624. Inc(Result.Exponent, C);
  625. end;
  626. // Calculate number of digits we have from str
  627. if BeforeDot then
  628. N := N - Start - 1
  629. else
  630. N := N - Start - 2;
  631. L := Length(Result.Digits);
  632. if N<L then
  633. Result.Digits[N]:='0'; //Zero remaining space
  634. if Decimals + Result.Exponent < Precision Then //After this it is the same as in FloatToDecimal
  635. N := Decimals + Result.Exponent
  636. Else
  637. N := Precision;
  638. if N >= L Then
  639. N := L-1;
  640. if N = 0 Then
  641. begin
  642. if Result.Digits[0] >= '5' Then
  643. begin
  644. Result.Digits[0] := '1';
  645. Result.Digits[1] := #0;
  646. Inc(Result.Exponent);
  647. end
  648. Else
  649. Result.Digits[0] := #0;
  650. end //N=0
  651. Else if N > 0 Then
  652. begin
  653. if Result.Digits[N] >= '5' Then
  654. begin
  655. Repeat
  656. Result.Digits[N] := #0;
  657. Dec(N);
  658. // Writeln(N,': ',Result.Digits[N],', Rounding to : ',Rounds[StrToInt(Result.Digits[N])]);
  659. Result.Digits[N]:=Rounds[StrToInt(Result.Digits[N])];
  660. Until (N = 0) Or (Result.Digits[N] < ':');
  661. If Result.Digits[0] = ':' Then
  662. begin
  663. Result.Digits[0] := '1';
  664. Inc(Result.Exponent);
  665. end;
  666. end
  667. Else
  668. begin
  669. Result.Digits[N] := '0';
  670. While (N > -1) And (Result.Digits[N] = '0') Do
  671. begin
  672. Result.Digits[N] := #0;
  673. Dec(N);
  674. end;
  675. end;
  676. end //N>0
  677. Else
  678. Result.Digits[0] := #0;
  679. if (Result.Digits[0] = #0) and
  680. not GotNonZeroBeforeDot then
  681. begin
  682. Result.Exponent := 0;
  683. Result.Negative := False;
  684. end;
  685. end;
  686. function FloatToStr(Value: Double): String;
  687. begin
  688. Result:=FloatToStrF(Value,ffGeneral,15,0);
  689. end;
  690. Function TryStrToFloat(const S : String; Out res : Double) : Boolean;
  691. Var
  692. J : JSValue;
  693. N : String;
  694. begin
  695. N:=S;
  696. // Delocalize
  697. if (ThousandSeparator <>'') then
  698. N:=StringReplace(N,ThousandSeparator,'',[rfReplaceAll]);
  699. if (DecimalSeparator<>'.') then
  700. N:=StringReplace(N,DecimalSeparator,'.',[]);
  701. J:=parseFloat(N);
  702. Result:=Not jsIsNaN(J);
  703. if Result then
  704. Res:=Double(J);
  705. end;
  706. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  707. begin
  708. if not TryStrToFloat(S,Result) then
  709. Result:=aDef;
  710. end;
  711. Function StrToFloat(const S : String) : Double;
  712. begin
  713. if not TryStrToFloat(S,Result) then
  714. Raise EConvertError.CreateFmt(SErrInvalidFloat,[S]);
  715. end;
  716. function FormatFloat(Fmt: String; aValue: Double): String;
  717. Type
  718. TPosArray = Array of Integer;
  719. const
  720. MaxPrecision = 18; // Extended precision
  721. var
  722. // Input in usable format
  723. E : Extended; // Value as extended.
  724. FV: TFloatRec; // Value as floatrec.
  725. Section : String; // Format can contain 3 sections, semicolon separated: Pos;Neg;Zero. This is the one to use.
  726. SectionLength : Integer; // Length of section.
  727. // Calculated based on section. Static during output
  728. ThousandSep: Boolean; // Thousands separator detected in format ?
  729. IsScientific: Boolean; // Use Scientific notation ? (E detected in format)
  730. DecimalPos: Integer; // Position of decimal point in pattern.
  731. FirstDigit: Integer; // First actual digit in input (# or 0), relative to decimal point
  732. LastDigit: Integer; // Last required (0) digit, relative to decimal point
  733. RequestedDigits: Integer; // Number of requested digits, # and 0 alike
  734. ExpSize : Integer; // Number of digits in exponent
  735. Available: Integer; // Available digits in FV.
  736. // These change during output loop
  737. Current: Integer; // Current digit in available digits
  738. PadZeroes: Integer; // Difference in requested digits before comma and exponent, needs to be padded with zeroes.
  739. DistToDecimal: Integer; // Place of current digit, relative to decimal point taking in account PadZeroes!
  740. Procedure InitVars;
  741. begin
  742. E:=aValue;
  743. Section:='';
  744. SectionLength:=0;
  745. ThousandSep:=false;
  746. IsScientific:=false;
  747. DecimalPos:=0;
  748. FirstDigit:=MaxInt;
  749. LastDigit:=0;
  750. RequestedDigits:=0;
  751. ExpSize:=0;
  752. Available:=-1;
  753. end;
  754. procedure ToResult(const AChar: Char);
  755. begin
  756. Result:=Result+AChar;
  757. end;
  758. procedure AddToResult(const AStr: String);
  759. begin
  760. Result:=Result+AStr;
  761. end;
  762. procedure WriteDigit(ADigit: Char);
  763. // Write a digit to result, prepend with decimalseparator or append with 1000 separator
  764. begin
  765. if ADigit=#0 then exit;
  766. // Writeln('WriteDigit: ',ADigit,', DistToDecimal: ',DistToDecimal);
  767. Dec(DistToDecimal);
  768. // -1 -> we've arrived behind the decimal
  769. if (DistToDecimal=-1) then
  770. begin
  771. AddToResult(DecimalSeparator);
  772. ToResult(ADigit);
  773. end
  774. else
  775. begin
  776. // We're still before the decimal.
  777. ToResult(ADigit);
  778. if ThousandSep and ((DistToDecimal mod 3)=0) and (DistToDecimal>1) then
  779. AddToResult(ThousandSeparator);
  780. end;
  781. end;
  782. Function GetDigit : Char;
  783. // Return next digit from available digits.
  784. // May return #0 if none available.
  785. // Will return '0' if applicable.
  786. begin
  787. // Writeln(' DistToDecimal <= LastDigit : ',DistToDecimal,' < ',LastDigit,' have digit: ',Current<=Available, '(',Current,')');
  788. Result:=#0;
  789. if (Current<=Available) then
  790. begin
  791. Result:=FV.Digits[Current];
  792. Inc(Current);
  793. end
  794. else if (DistToDecimal <= LastDigit) then
  795. Dec(DistToDecimal)
  796. else
  797. Result:='0';
  798. // Writeln('GetDigit ->: ',Result);
  799. end;
  800. procedure CopyDigit;
  801. // Copy a digit (#, 0) to the output with the correct value
  802. begin
  803. // Writeln('CopyDigit ');
  804. if (PadZeroes=0) then
  805. WriteDigit(GetDigit) // No shift needed, just copy what is available.
  806. else if (PadZeroes<0) then
  807. begin
  808. // We must prepend zeroes
  809. Inc(PadZeroes);
  810. if (DistToDecimal<=FirstDigit) then
  811. WriteDigit('0')
  812. else
  813. Dec(DistToDecimal);
  814. end
  815. else
  816. begin
  817. // We must append zeroes
  818. while PadZeroes > 0 do
  819. begin
  820. WriteDigit(GetDigit);
  821. Dec(PadZeroes);
  822. end;
  823. WriteDigit(GetDigit);
  824. end;
  825. end;
  826. Function GetSections(Var SP : TPosArray) : Integer;
  827. var
  828. FL : Integer;
  829. i : Integer;
  830. C,Q : Char;
  831. inQuote : Boolean;
  832. begin
  833. Result:=1;
  834. SP[1]:=-1;
  835. SP[2]:=-1;
  836. SP[3]:=-1;
  837. inQuote:=False;
  838. Q:=#0;
  839. I:=1;
  840. FL:=Length(Fmt);
  841. while (I<=FL) do
  842. begin
  843. C:=Fmt[I];
  844. case C of
  845. ';':
  846. begin
  847. if not InQuote then
  848. begin
  849. if Result>3 then
  850. Raise Exception.Create('Invalid float format');
  851. SP[Result]:=I+1;
  852. Inc(Result);
  853. end;
  854. end;
  855. '"','''':
  856. begin
  857. if InQuote then
  858. InQuote:=C<>Q
  859. else
  860. begin
  861. InQuote:=True;
  862. Q:=C;
  863. end;
  864. end;
  865. end;
  866. Inc(I);
  867. end;
  868. if SP[Result]=-1 then
  869. SP[Result]:=FL+1;
  870. end;
  871. Procedure AnalyzeFormat;
  872. var
  873. I,Len: Integer;
  874. Q,C: Char;
  875. InQuote : Boolean;
  876. begin
  877. Len:=Length(Section);
  878. I:=1;
  879. InQuote:=False;
  880. Q:=#0;
  881. while (I<=Len) do
  882. begin
  883. C:=Section[i];
  884. if C in ['"',''''] then
  885. begin
  886. if InQuote then
  887. InQuote:=C<>Q
  888. else
  889. begin
  890. InQuote:=True;
  891. Q:=C;
  892. end;
  893. end
  894. else if not InQuote then
  895. case C of
  896. '.':
  897. if (DecimalPos=0) then
  898. DecimalPos:=RequestedDigits+1;
  899. ',':
  900. ThousandSep:=ThousandSeparator<>#0;
  901. 'e', 'E':
  902. begin
  903. Inc(I);
  904. if (I<Len) then
  905. begin
  906. C:=Section[i];
  907. IsScientific:=C in ['-','+'];
  908. if IsScientific then
  909. while (I<Len) and (Section[i+1]='0') do
  910. begin
  911. Inc(ExpSize);
  912. Inc(I);
  913. end;
  914. if ExpSize>4 then
  915. ExpSize:=4;
  916. end;
  917. end;
  918. '#':
  919. Inc(RequestedDigits);
  920. '0':
  921. begin
  922. if RequestedDigits<FirstDigit then
  923. FirstDigit:=RequestedDigits+1;
  924. Inc(RequestedDigits);
  925. LastDigit:=RequestedDigits+1;
  926. end;
  927. end;
  928. Inc(I);
  929. end;
  930. if DecimalPos=0 then
  931. DecimalPos:=RequestedDigits+1;
  932. // Writeln('LastDigit: ',DecimalPos,'-',LastDigit);
  933. LastDigit:=DecimalPos-LastDigit;
  934. if LastDigit>0 then
  935. LastDigit:=0;
  936. // Writeln('FirstDigit: ',DecimalPos,'-',FirstDigit);
  937. FirstDigit:=DecimalPos-FirstDigit;
  938. if FirstDigit<0 then
  939. FirstDigit:=0;
  940. end;
  941. Function ValueOutSideScope : Boolean;
  942. begin
  943. With FV do
  944. Result:=((Exponent >= 18) and (not IsScientific)) or (Exponent = $7FF) or (Exponent = $800)
  945. end;
  946. Procedure CalcRunVars;
  947. Var
  948. D,P: Integer;
  949. begin
  950. if IsScientific then
  951. begin
  952. P:=RequestedDigits;
  953. D:=9999;
  954. end
  955. else
  956. begin
  957. P:=MaxPrecision;
  958. D:=RequestedDigits-DecimalPos+1;
  959. end;
  960. FV:=FloatToDecimal(aValue,P,D);
  961. DistToDecimal:=DecimalPos-1;
  962. if IsScientific then
  963. PadZeroes:=0 // No padding.
  964. else
  965. begin
  966. PadZeroes:=FV.Exponent-(DecimalPos-1);
  967. if (PadZeroes>=0) then
  968. DistToDecimal:=FV.Exponent
  969. end;
  970. // Writeln('PadZeroes : ',PadZeroes, ', DistToDecimal : ',DistToDecimal);
  971. Available:=-1;
  972. while (Available<High(FV.Digits)) and (FV.Digits[Available+1]<>#0) do
  973. Inc(Available);
  974. // Writeln('Available: ',Available);
  975. end;
  976. Function FormatExponent(ASign: Char; aExponent: Integer) : String;
  977. begin
  978. Result:=IntToStr(aExponent);
  979. Result:=StringOfChar('0',ExpSize-Length(Result))+Result;
  980. if (aExponent<0) then
  981. Result:='-'+Result
  982. else if (aExponent>0) and (aSign='+') then
  983. Result:=aSign+Result;
  984. end;
  985. var
  986. I,S : Integer;
  987. C,Q : Char;
  988. PA : TPosArray;
  989. InLiteral : Boolean;
  990. begin
  991. SetLength(PA,4);
  992. Result:='';
  993. Initvars;
  994. // What section to use ?
  995. if (E>0) then
  996. S:=1
  997. else if (E<0) then
  998. S:=2
  999. else
  1000. S:=3;
  1001. PA[0]:=0;
  1002. I:=GetSections(PA);
  1003. if (I<S) or (PA[S]-PA[S-1]=0) then
  1004. S:=1;
  1005. // Extract correct section
  1006. SectionLength:=PA[S]-PA[S-1]-1;
  1007. Section:=Copy(Fmt,PA[S-1]+1,SectionLength);
  1008. SetLength(Section,SectionLength);
  1009. // Writeln('Section ',I,' : "',Section,'" ',SectionLength);
  1010. AnalyzeFormat;
  1011. // Writeln('RequestedDigits: ',RequestedDigits,', DecimalPos : ',DecimalPos,', LastDigit: ',LastDigit,', FirstDigit: ',FirstDigit);
  1012. CalcRunVars;
  1013. // If we cannot process value using current settings, fallback
  1014. if (SectionLength=0) or ValueOutSideScope then
  1015. begin
  1016. asm
  1017. Section=E.toPrecision(15);
  1018. end;
  1019. Result:=Section;
  1020. end;
  1021. // Get Started
  1022. I:=1;
  1023. Current:=0;
  1024. Q:=' ';
  1025. InLiteral:=False;
  1026. if (FV.Negative) and (S=1) then
  1027. ToResult('-');
  1028. while (I<=SectionLength) do
  1029. begin
  1030. C:=Section[i];
  1031. // Writeln('Analyzing pos ',I,': "',C,'"');
  1032. If (C in ['"', '''']) then
  1033. begin
  1034. if InLiteral then
  1035. InLiteral:=C<>Q
  1036. else
  1037. begin
  1038. inLiteral:=True;
  1039. Q:=C;
  1040. end;
  1041. end
  1042. else if InLiteral then
  1043. ToResult(C)
  1044. else
  1045. case C of
  1046. '0', '#':
  1047. CopyDigit;
  1048. '.', ',':
  1049. ; // Do nothing, handled by CopyDigit
  1050. 'e', 'E':
  1051. begin
  1052. ToResult(C); // Always needed
  1053. Inc(I);
  1054. if I<=Length(Section) then
  1055. begin
  1056. C:=Section[I];
  1057. if (C in ['+','-']) then
  1058. begin
  1059. AddToResult(FormatExponent(C,FV.Exponent-DecimalPos+1));
  1060. // Skip rest
  1061. while (I<SectionLength) and (Section[i+1]='0') do
  1062. Inc(I);
  1063. end;
  1064. end;
  1065. end;
  1066. else
  1067. ToResult(C);
  1068. end;
  1069. Inc(i);
  1070. end;
  1071. end;
  1072. function StrToBool(const S: String): Boolean;
  1073. begin
  1074. if not(TryStrToBool(S,Result)) then
  1075. raise EConvertError.CreateFmt(SInvalidBoolean,[S]);
  1076. end;
  1077. procedure CheckBoolStrs;
  1078. begin
  1079. if Length(TrueBoolStrs)=0 then
  1080. begin
  1081. SetLength(TrueBoolStrs,1);
  1082. TrueBoolStrs[0]:='True';
  1083. end;
  1084. if Length(FalseBoolStrs)=0 then
  1085. begin
  1086. SetLength(FalseBoolStrs,1);
  1087. FalseBoolStrs[0]:='False';
  1088. end;
  1089. end;
  1090. function BoolToStr(B: Boolean; UseBoolStrs: Boolean): string;
  1091. begin
  1092. if UseBoolStrs Then
  1093. begin
  1094. CheckBoolStrs;
  1095. if B then
  1096. Result:=TrueBoolStrs[0]
  1097. else
  1098. Result:=FalseBoolStrs[0];
  1099. end else
  1100. if B then
  1101. Result:='-1'
  1102. else
  1103. Result:='0';
  1104. end;
  1105. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  1106. begin
  1107. if B then Result:=TrueS else Result:=FalseS;
  1108. end;
  1109. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  1110. begin
  1111. if not TryStrToBool(S,Result) then
  1112. Result:=Default;
  1113. end;
  1114. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  1115. Var
  1116. Temp : String;
  1117. I : Longint;
  1118. D : Double;
  1119. Code: integer;
  1120. begin
  1121. Temp:=uppercase(S);
  1122. Val(Temp,D,code);
  1123. Result:=true;
  1124. If Code=0 then
  1125. Value:=(D<>0.0)
  1126. else
  1127. begin
  1128. CheckBoolStrs;
  1129. for I:=low(TrueBoolStrs) to High(TrueBoolStrs) do
  1130. if Temp=uppercase(TrueBoolStrs[I]) then
  1131. begin
  1132. Value:=true;
  1133. exit;
  1134. end;
  1135. for I:=low(FalseBoolStrs) to High(FalseBoolStrs) do
  1136. if Temp=uppercase(FalseBoolStrs[I]) then
  1137. begin
  1138. Value:=false;
  1139. exit;
  1140. end;
  1141. Result:=false;
  1142. end;
  1143. end;
  1144. function UpperCase(const s: String): String; assembler;
  1145. asm
  1146. return s.toUpperCase();
  1147. end;
  1148. function LowerCase(const s: String): String; assembler;
  1149. asm
  1150. return s.toLowerCase();
  1151. end;
  1152. function CompareStr(const s1, s2: String): Integer; assembler;
  1153. asm
  1154. var l1 = s1.length;
  1155. var l2 = s2.length;
  1156. if (l1<=l2){
  1157. var s = s2.substr(0,l1);
  1158. if (s1<s){ return -1;
  1159. } else if (s1>s){ return 1;
  1160. } else { return l1<l2 ? -1 : 0; };
  1161. } else {
  1162. var s = s1.substr(0,l2);
  1163. if (s<s2){ return -1;
  1164. } else { return 1; };
  1165. };
  1166. end;
  1167. function SameStr(const s1, s2: String): Boolean; assembler;
  1168. asm
  1169. return s1 == s2;
  1170. end;
  1171. function CompareText(const s1, s2: String): Integer; assembler;
  1172. asm
  1173. var l1 = s1.toLowerCase();
  1174. var l2 = s2.toLowerCase();
  1175. if (l1>l2){ return 1;
  1176. } else if (l1<l2){ return -1;
  1177. } else { return 0; }
  1178. end;
  1179. function SameText(const s1, s2: String): Boolean; assembler;
  1180. asm
  1181. return s1.toLowerCase() == s2.toLowerCase();
  1182. end;
  1183. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  1184. asm
  1185. return s1.localeCompare(s2);
  1186. end;
  1187. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  1188. asm
  1189. return s1.localeCompare(s2) == 0;
  1190. end;
  1191. function AnsiCompareStr(const s1, s2: String): Integer;
  1192. begin
  1193. {$IFDEF ECMAScript6}
  1194. Result:=CompareText(TJSString(s1).normalize(),TJSString(s1).normalize());
  1195. {$ELSE}
  1196. Result:=CompareText(s1,s2);
  1197. {$ENDIF}
  1198. end;
  1199. procedure AppendStr(var Dest: String; const S: string);
  1200. begin
  1201. Dest:=Dest+S;
  1202. end;
  1203. Const
  1204. feInvalidFormat = 1;
  1205. feMissingArgument = 2;
  1206. feInvalidArgIndex = 3;
  1207. Procedure DoFormatError (ErrCode : Longint;const fmt: String);
  1208. begin
  1209. //!! must be changed to contain format string...
  1210. Case ErrCode of
  1211. feInvalidFormat : raise EConvertError.Createfmt(SInvalidFormat,[Fmt]);
  1212. feMissingArgument : raise EConvertError.Createfmt(SArgumentMissing,[Fmt]);
  1213. feInvalidArgIndex : raise EConvertError.Createfmt(SInvalidArgIndex,[Fmt]);
  1214. end;
  1215. end;
  1216. Const
  1217. maxdigits = 15;
  1218. Function ReplaceDecimalSep(S: String; Const DS : string) : string;
  1219. Var
  1220. P : Integer;
  1221. begin
  1222. P:=Pos('.',S);
  1223. if P>0 then
  1224. Result:=Copy(S,1,P-1)+DS+Copy(S,P+1,Length(S)-P)
  1225. else
  1226. Result:=S;
  1227. end;
  1228. function FormatGeneralFloat(Value : double; Precision : Integer; DS : String) : string;
  1229. Var
  1230. P, PE, Q, Exponent: Integer;
  1231. Begin
  1232. If (Precision = -1) Or (Precision > maxdigits) Then
  1233. Precision := maxdigits;
  1234. { First convert to scientific format, with correct precision }
  1235. Str(Value:precision+7, Result);
  1236. { Delete leading spaces }
  1237. Result:=TrimLeft(Result);
  1238. P:=Pos('.',Result);
  1239. if P=0 then
  1240. exit;
  1241. { Consider removing exponent }
  1242. PE:=Pos('E',Result);
  1243. if PE=0 then
  1244. begin
  1245. Result:=ReplaceDecimalSep(Result,DS);
  1246. exit;
  1247. end;
  1248. { Read exponent }
  1249. Q:=PE+2;
  1250. Exponent := 0;
  1251. while (Q <= Length(Result)) do
  1252. begin
  1253. Exponent := Exponent*10 + Ord(Result[Q])-Ord('0');
  1254. Inc(Q);
  1255. end;
  1256. if Result[PE+1] = '-' then
  1257. Exponent := -Exponent;
  1258. if (P+Exponent < PE) and (Exponent > -6) then
  1259. begin
  1260. { OK to remove exponent }
  1261. SetLength(Result,PE-1); { Trim exponent }
  1262. if Exponent >= 0 then
  1263. begin
  1264. { Shift point to right }
  1265. for Q := 0 to Exponent-1 do
  1266. begin
  1267. Result[P] := Result[P+1];
  1268. Inc(P);
  1269. end;
  1270. Result[P] := '.';
  1271. P := 1;
  1272. if Result[P] = '-' then
  1273. Inc(P);
  1274. while (Result[P] = '0') and (P < Length(Result)) and (Copy(Result,P+1,Length(DS))<>DS) do
  1275. { Trim leading zeros; conversion above should not give any, but occasionally does
  1276. because of rounding }
  1277. System.Delete(Result,P,1);
  1278. end
  1279. else
  1280. begin
  1281. { Add zeros at start }
  1282. Insert(Copy('00000',1,-Exponent),Result,P-1);
  1283. Result[P-Exponent] := Result[P-Exponent-1]; { Copy leading digit }
  1284. Result[P] := '.';
  1285. if Exponent <> -1 then
  1286. Result[P-Exponent-1] := '0';
  1287. end;
  1288. { Remove trailing zeros }
  1289. Q := Length(Result);
  1290. while (Q > 0) and (Result[Q] = '0') do
  1291. Dec(Q);
  1292. if Result[Q] = '.' then
  1293. Dec(Q); { Remove trailing decimal point }
  1294. if (Q = 0) or ((Q=1) and (Result[1] = '-')) then
  1295. Result := '0'
  1296. else
  1297. SetLength(Result,Q);
  1298. end
  1299. else
  1300. begin
  1301. { Need exponent, but remove superfluous characters }
  1302. { Delete trailing zeros }
  1303. while Result[PE-1] = '0' do
  1304. begin
  1305. System.Delete(Result,PE-1,1);
  1306. Dec(PE);
  1307. end;
  1308. { If number ends in decimal point, remove it }
  1309. if Result[PE-1] = DS then
  1310. begin
  1311. System.Delete(Result,PE-1,1);
  1312. Dec(PE);
  1313. end;
  1314. { delete superfluous + in exponent }
  1315. if Result[PE+1]='+' then
  1316. System.Delete(Result,PE+1,1)
  1317. else
  1318. Inc(PE);
  1319. while Result[PE+1] = '0' do
  1320. { Delete leading zeros in exponent }
  1321. System.Delete(Result,PE+1,1)
  1322. end;
  1323. Result:=ReplaceDecimalSep(Result,DS)
  1324. end;
  1325. function FormatExponentFloat(Value : double; Precision,Digits : Integer;DS : String) : string;
  1326. Var
  1327. P: Integer;
  1328. Begin
  1329. DS:=DecimalSeparator;
  1330. If (Precision = -1) Or (Precision > maxdigits) Then
  1331. Precision := maxdigits;
  1332. Str(Value:Precision+7, Result);
  1333. { Delete leading spaces }
  1334. while Result[1] = ' ' do
  1335. System.Delete(Result, 1, 1);
  1336. P:=Pos('E',Result);
  1337. if P=0 then
  1338. begin
  1339. Result:=ReplaceDecimalSep(Result,DS);
  1340. exit;
  1341. end;
  1342. Inc(P, 2);
  1343. if Digits > 4 then
  1344. Digits:=4;
  1345. Digits:=Length(Result) - P - Digits + 1;
  1346. if Digits < 0 then
  1347. insert(copy('0000',1,-Digits),Result,P)
  1348. else
  1349. while (Digits > 0) and (Result[P] = '0') do
  1350. begin
  1351. System.Delete(Result, P, 1);
  1352. if P > Length(Result) then
  1353. begin
  1354. System.Delete(Result, P - 2, 2);
  1355. break;
  1356. end;
  1357. Dec(Digits);
  1358. end;
  1359. Result:=ReplaceDecimalSep(Result,DS);
  1360. End;
  1361. function FormatFixedFloat(Value : double; Digits : Integer; DS : String) : string;
  1362. Begin
  1363. If Digits = -1 Then
  1364. Digits := 2
  1365. Else If Digits > 18 Then
  1366. Digits := 18;
  1367. Str(Value:0:Digits, Result);
  1368. if (Result<>'') and (Result[1]=' ') then
  1369. Delete(Result,1,1);
  1370. Result:=ReplaceDecimalSep(Result,DS);
  1371. end;
  1372. function FormatNumberFloat(Value : double; Digits : Integer; DS,TS : String) : string;
  1373. Var
  1374. P : integer;
  1375. Begin
  1376. If Digits = -1 Then
  1377. Digits := 2
  1378. else If Digits > maxdigits Then
  1379. Digits := maxdigits;
  1380. Str(Value:0:Digits, Result);
  1381. if (Result<>'') and (Result[1]=' ') then
  1382. Delete(Result,1,1);
  1383. P:=Pos('.',Result);
  1384. Result:=ReplaceDecimalSep(Result,DS);
  1385. Dec(P,3);
  1386. if (TS<>'') and (TS<>#0) then
  1387. While (P>1) Do
  1388. Begin
  1389. If (Result[P-1] <> '-') Then
  1390. Insert(TS, Result, P);
  1391. Dec(P, 3);
  1392. End;
  1393. End;
  1394. function RemoveLeadingNegativeSign(var AValue: String; DS : String): Boolean;
  1395. // removes negative sign in case when result is zero eg. -0.00
  1396. var
  1397. i: PtrInt;
  1398. TS: String;
  1399. StartPos: PtrInt;
  1400. begin
  1401. Result:=False;
  1402. StartPos := 2;
  1403. TS := ThousandSeparator;
  1404. for i :=StartPos to length(AValue) do
  1405. begin
  1406. Result := (AValue[i] in ['0', DS, 'E', '+']) or (aValue=TS);
  1407. if not Result then
  1408. break;
  1409. end;
  1410. if (Result) then
  1411. Delete(AValue, 1, 1);
  1412. end;
  1413. Function FormatNumberCurrency(const Value : Currency; Digits : Integer; DS,TS : String) : string;
  1414. Var
  1415. Negative: Boolean;
  1416. P : Integer;
  1417. Begin
  1418. If Digits = -1 Then
  1419. Digits := CurrencyDecimals
  1420. Else If Digits > 18 Then
  1421. Digits := 18;
  1422. Str(Value:0:Digits, Result);
  1423. Negative:=Result[1] = '-';
  1424. if Negative then
  1425. System.Delete(Result, 1, 1);
  1426. P := Pos('.', Result);
  1427. If P <> 0 Then
  1428. Result:=ReplaceDecimalSep(Result,DS)
  1429. else
  1430. P := Length(Result)+1;
  1431. Dec(P, 3);
  1432. While (P > 1) Do
  1433. Begin
  1434. If ThousandSeparator<>#0 Then
  1435. Insert(FormatSettings.ThousandSeparator, Result, P);
  1436. Dec(P, 3);
  1437. End;
  1438. if (length(Result) > 1) and Negative then
  1439. Negative := not RemoveLeadingNegativeSign(Result,DS);
  1440. If Not Negative Then
  1441. Case CurrencyFormat Of
  1442. 0: Result := CurrencyString + Result;
  1443. 1: Result := Result + CurrencyString;
  1444. 2: Result := CurrencyString + ' ' + Result;
  1445. 3: Result := Result + ' ' + CurrencyString;
  1446. end
  1447. else
  1448. Case NegCurrFormat Of
  1449. 0: Result := '(' + CurrencyString + Result + ')';
  1450. 1: Result := '-' + CurrencyString + Result;
  1451. 2: Result := CurrencyString + '-' + Result;
  1452. 3: Result := CurrencyString + Result + '-';
  1453. 4: Result := '(' + Result + CurrencyString + ')';
  1454. 5: Result := '-' + Result + CurrencyString;
  1455. 6: Result := Result + '-' + CurrencyString;
  1456. 7: Result := Result + CurrencyString + '-';
  1457. 8: Result := '-' + Result + ' ' + CurrencyString;
  1458. 9: Result := '-' + CurrencyString + ' ' + Result;
  1459. 10: Result := Result + ' ' + CurrencyString + '-';
  1460. 11: Result := CurrencyString + ' ' + Result + '-';
  1461. 12: Result := CurrencyString + ' ' + '-' + Result;
  1462. 13: Result := Result + '-' + ' ' + CurrencyString;
  1463. 14: Result := '(' + CurrencyString + ' ' + Result + ')';
  1464. 15: Result := '(' + Result + ' ' + CurrencyString + ')';
  1465. end;
  1466. if TS='' then ;
  1467. end;
  1468. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  1469. Var
  1470. DS: string;
  1471. Begin
  1472. DS:=DecimalSeparator;
  1473. Case format Of
  1474. ffGeneral:
  1475. Result:=FormatGeneralFloat(Value,Precision,DS);
  1476. ffExponent:
  1477. Result:=FormatExponentFloat(Value,Precision,Digits,DS);
  1478. ffFixed:
  1479. Result:=FormatFixedFloat(Value,Digits,DS);
  1480. ffNumber:
  1481. Result:=FormatNumberFloat(Value,Digits,DS,ThousandSeparator);
  1482. ffCurrency:
  1483. Result:=FormatNumberCurrency(Value,Digits,DS,ThousandSeparator);
  1484. end;
  1485. if (Format<>ffCurrency) and (length(Result)>1) and (Result[1]='-') then
  1486. RemoveLeadingNegativeSign(Result,DS);
  1487. end;
  1488. function Format (const Fmt: String; const Args: array of jsvalue): String;
  1489. Var ChPos,OldPos,ArgPos,DoArg,Len : SizeInt;
  1490. Hs,ToAdd : String;
  1491. Index : SizeInt;
  1492. Width,Prec : Longint;
  1493. Left : Boolean;
  1494. Fchar : char;
  1495. vq : nativeint;
  1496. {
  1497. ReadFormat reads the format string. It returns the type character in
  1498. uppercase, and sets index, Width, Prec to their correct values,
  1499. or -1 if not set. It sets Left to true if left alignment was requested.
  1500. In case of an error, DoFormatError is called.
  1501. }
  1502. Function ReadFormat : Char;
  1503. Var Value : NativeInt;
  1504. Procedure ReadInteger;
  1505. var
  1506. Code: integer;
  1507. ArgN: SizeInt;
  1508. begin
  1509. If Value<>-1 then exit; // Was already read.
  1510. OldPos:=ChPos;
  1511. While (ChPos<=Len) and
  1512. (Fmt[ChPos]<='9') and (Fmt[ChPos]>='0') do inc(ChPos);
  1513. If ChPos>len then
  1514. DoFormatError(feInvalidFormat,Fmt);
  1515. If Fmt[ChPos]='*' then
  1516. begin
  1517. if Index=-1 then
  1518. ArgN:=Argpos
  1519. else
  1520. begin
  1521. ArgN:=Index;
  1522. Inc(Index);
  1523. end;
  1524. If (ChPos>OldPos) or (ArgN>High(Args)) then
  1525. DoFormatError(feInvalidFormat,Fmt);
  1526. ArgPos:=ArgN+1;
  1527. if IsNumber(Args[ArgN]) and IsInteger(Args[ArgN]) then
  1528. Value:=Integer(Args[ArgN])
  1529. else
  1530. DoFormatError(feInvalidFormat,Fmt);
  1531. Inc(ChPos);
  1532. end
  1533. else
  1534. begin
  1535. If (OldPos<ChPos) Then
  1536. begin
  1537. Val (Copy(Fmt,OldPos,ChPos-OldPos),value,code);
  1538. // This should never happen !!
  1539. If Code>0 then DoFormatError (feInvalidFormat,Fmt);
  1540. end
  1541. else
  1542. Value:=-1;
  1543. end;
  1544. end;
  1545. Procedure ReadIndex;
  1546. begin
  1547. If Fmt[ChPos]<>':' then
  1548. ReadInteger
  1549. else
  1550. value:=0; // Delphi undocumented behaviour, assume 0, #11099
  1551. If Fmt[ChPos]=':' then
  1552. begin
  1553. If Value=-1 then DoFormatError(feMissingArgument,Fmt);
  1554. Index:=Value;
  1555. Value:=-1;
  1556. Inc(ChPos);
  1557. end;
  1558. end;
  1559. Procedure ReadLeft;
  1560. begin
  1561. If Fmt[ChPos]='-' then
  1562. begin
  1563. left:=True;
  1564. Inc(ChPos);
  1565. end
  1566. else
  1567. Left:=False;
  1568. end;
  1569. Procedure ReadWidth;
  1570. begin
  1571. ReadInteger;
  1572. If Value<>-1 then
  1573. begin
  1574. Width:=Value;
  1575. Value:=-1;
  1576. end;
  1577. end;
  1578. Procedure ReadPrec;
  1579. begin
  1580. If Fmt[ChPos]='.' then
  1581. begin
  1582. inc(ChPos);
  1583. ReadInteger;
  1584. If Value=-1 then
  1585. Value:=0;
  1586. prec:=Value;
  1587. end;
  1588. end;
  1589. begin
  1590. Index:=-1;
  1591. Width:=-1;
  1592. Prec:=-1;
  1593. Value:=-1;
  1594. inc(ChPos);
  1595. If Fmt[ChPos]='%' then
  1596. begin
  1597. Result:='%';
  1598. exit; // VP fix
  1599. end;
  1600. ReadIndex;
  1601. ReadLeft;
  1602. ReadWidth;
  1603. ReadPrec;
  1604. Result:=Upcase(Fmt[ChPos]);
  1605. end;
  1606. function Checkarg (AT : TJSValueType; err:boolean):boolean;
  1607. {
  1608. Check if argument INDEX is of correct type (AT)
  1609. If Index=-1, ArgPos is used, and argpos is augmented with 1
  1610. DoArg is set to the argument that must be used.
  1611. }
  1612. begin
  1613. result:=false;
  1614. if Index=-1 then
  1615. DoArg:=Argpos
  1616. else
  1617. DoArg:=Index;
  1618. ArgPos:=DoArg+1;
  1619. If (Doarg>High(Args)) or (GetValueTYpe(Args[Doarg])<>AT) then
  1620. begin
  1621. if err then
  1622. DoFormatError(feInvalidArgindex,Fmt);
  1623. dec(ArgPos);
  1624. exit;
  1625. end;
  1626. result:=true;
  1627. end;
  1628. begin
  1629. Result:='';
  1630. Len:=Length(Fmt);
  1631. ChPos:=1;
  1632. OldPos:=1;
  1633. ArgPos:=0;
  1634. While ChPos<=len do
  1635. begin
  1636. While (ChPos<=Len) and (Fmt[ChPos]<>'%') do
  1637. inc(ChPos);
  1638. If ChPos>OldPos Then
  1639. Result:=Result+Copy(Fmt,OldPos,ChPos-Oldpos);
  1640. If ChPos<Len then
  1641. begin
  1642. FChar:=ReadFormat;
  1643. {$ifdef fmtdebug}
  1644. DumpFormat(FCHar);
  1645. {$endif}
  1646. Case FChar of
  1647. 'D' : begin
  1648. Checkarg(jvtinteger,true);
  1649. toAdd:=IntToStr(NativeInt(Args[DoArg]));
  1650. Width:=Abs(width);
  1651. Index:=Prec-Length(ToAdd);
  1652. If ToAdd[1]<>'-' then
  1653. ToAdd:=StringOfChar('0',Index)+ToAdd
  1654. else
  1655. // + 1 to accomodate for - sign in length !!
  1656. Insert(StringOfChar('0',Index+1),toadd,2);
  1657. end;
  1658. 'U' : begin
  1659. Checkarg(jvtinteger,True);
  1660. if NativeInt(Args[Doarg])<0 then
  1661. DoFormatError(feInvalidArgindex,Fmt);
  1662. Toadd:=IntToStr(NativeInt(Args[Doarg]));
  1663. Width:=Abs(width);
  1664. Index:=Prec-Length(ToAdd);
  1665. ToAdd:=StringOfChar('0',Index)+ToAdd
  1666. end;
  1667. 'E' : begin
  1668. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1669. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1670. end;
  1671. 'F' : begin
  1672. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1673. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1674. end;
  1675. 'G' : begin
  1676. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1677. ToAdd:=FloatToStrF(Double(Args[doarg]),ffGeneral,Prec,3);
  1678. end;
  1679. 'N' : begin
  1680. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1681. ToAdd:=FloatToStrF(Double(Args[doarg]),ffNumber,9999,Prec);
  1682. end;
  1683. 'M' : begin
  1684. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1685. ToAdd:=FloatToStrF(Double(Args[doarg]),ffCurrency,9999,Prec);
  1686. end;
  1687. 'S' : begin
  1688. CheckArg(jvtString,true);
  1689. hs:=String(Args[doarg]);
  1690. Index:=Length(hs);
  1691. If (Prec<>-1) and (Index>Prec) then
  1692. Index:=Prec;
  1693. ToAdd:=Copy(hs,1,Index);
  1694. end;
  1695. 'P' : Begin
  1696. CheckArg(jvtInteger,true);
  1697. ToAdd:=IntToHex(NativeInt(Args[DoArg]),31);
  1698. end;
  1699. 'X' : begin
  1700. Checkarg(jvtinteger,true);
  1701. vq:=nativeInt(Args[Doarg]);
  1702. index:=31; // May need to adjust to NativeInt
  1703. If Prec>index then
  1704. ToAdd:=IntToHex(vq,index)
  1705. else
  1706. begin
  1707. // determine minimum needed number of hex digits.
  1708. Index:=1;
  1709. While (NativeInt(1) shl (Index*4)<=vq) and (index<16) do
  1710. inc(Index);
  1711. If Index>Prec then
  1712. Prec:=Index;
  1713. ToAdd:=IntToHex(vq,Prec);
  1714. end;
  1715. end;
  1716. '%': ToAdd:='%';
  1717. end;
  1718. If Width<>-1 then
  1719. If Length(ToAdd)<Width then
  1720. If not Left then
  1721. ToAdd:=StringOfChar(' ',Width-Length(ToAdd))+ToAdd
  1722. else
  1723. ToAdd:=ToAdd+StringOfChar(' ',Width-Length(ToAdd));
  1724. Result:=Result+ToAdd;
  1725. end;
  1726. inc(ChPos);
  1727. Oldpos:=ChPos;
  1728. end;
  1729. end;
  1730. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler;
  1731. asm
  1732. return s1.localeCompare(s2,locales) == 0;
  1733. end;
  1734. function NormalizeStr(const S: String; const Norm: String): String; assembler;
  1735. asm
  1736. return S.normalize(Norm);
  1737. end;
  1738. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  1739. const
  1740. Alpha = ['A'..'Z', 'a'..'z', '_'];
  1741. AlphaNum = Alpha + ['0'..'9'];
  1742. Dot = '.';
  1743. var
  1744. First: Boolean;
  1745. I, Len: Integer;
  1746. begin
  1747. Len := Length(Ident);
  1748. if Len < 1 then
  1749. Exit(False);
  1750. First := True;
  1751. Result:=false;
  1752. I:=1;
  1753. While I<=len do
  1754. begin
  1755. if First then
  1756. begin
  1757. if not (Ident[I] in Alpha) then exit;
  1758. First := False;
  1759. end
  1760. else if AllowDots and (Ident[I] = Dot) then
  1761. begin
  1762. if StrictDots then
  1763. begin
  1764. if I >= Len then exit;
  1765. First := True;
  1766. end;
  1767. end
  1768. else
  1769. if not (Ident[I] in AlphaNum) then exit;
  1770. I:=I+1;
  1771. end;
  1772. Result:=true;
  1773. end;
  1774. procedure FreeAndNil(var Obj);
  1775. var
  1776. o: TObject;
  1777. begin
  1778. o:=TObject(Obj);
  1779. if o=nil then exit;
  1780. TObject(Obj):=nil;
  1781. o.Destroy;
  1782. end;
  1783. { EVariantError }
  1784. constructor EVariantError.CreateCode(Code: Longint);
  1785. begin
  1786. ErrCode:=Code;
  1787. end;
  1788. { Exception }
  1789. constructor Exception.Create(const Msg: String);
  1790. begin
  1791. fMessage:=Msg;
  1792. end;
  1793. constructor Exception.CreateFmt(const Msg: string; const Args: array of JSValue);
  1794. begin
  1795. //writeln('Exception.CreateFmt START ',ClassName,' "',Msg,'" Args=',Args);
  1796. fMessage:=Format(Msg,Args);
  1797. //writeln('Exception.CreateFmt END ',ClassName,' "',Msg,'" fMessage=',fMessage);
  1798. end;
  1799. constructor Exception.CreateHelp(const Msg: String; AHelpContext: Integer);
  1800. begin
  1801. fMessage:=Msg;
  1802. fHelpContext:=AHelpContext;
  1803. end;
  1804. constructor Exception.CreateFmtHelp(const Msg: string;
  1805. const Args: array of JSValue; AHelpContext: Integer);
  1806. begin
  1807. fMessage:=Format(Msg,Args);
  1808. fHelpContext:=AHelpContext;
  1809. end;
  1810. function Exception.ToString: String;
  1811. begin
  1812. Result:=ClassName+': '+Message;
  1813. end;
  1814. Const
  1815. RESpecials = '([\[\]\(\)\\\.\*])';
  1816. Function StringReplace(aOriginal, aSearch, aReplace : string; Flags : TStringReplaceFlags) : String;
  1817. Var
  1818. REFlags : String;
  1819. REString : String;
  1820. begin
  1821. REFlags:='';
  1822. if rfReplaceAll in flags then
  1823. ReFlags:='g';
  1824. if rfIgnoreCase in flags then
  1825. ReFlags:=ReFlags+'i';
  1826. REString:=TJSString(aSearch).replace(TJSRegexp.new(RESpecials,'g'),'\$1');
  1827. Result:=TJSString(aOriginal).replace(TJSRegexp.new(REString,REFlags),aReplace);
  1828. end;
  1829. Function QuoteString(aOriginal : String; AQuote : Char) : String;
  1830. Var
  1831. REString : String;
  1832. begin
  1833. REString:=TJSString(aQuote).replace(TJSRegexp.new(aOriginal,'g'),'\\$1');
  1834. Result:=AQuote+TJSString(aOriginal).replace(TJSRegexp.new(REString,'g'),'$1\$1')+AQuote;
  1835. end;
  1836. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  1837. begin
  1838. Result:=False;
  1839. if (Index>0) and (Index<=Length(S)) then
  1840. Result:=Pos(S[Index],Delimiters)<>0; // Note we don't do MBCS yet
  1841. end;
  1842. function AdjustLineBreaks(const S: string): string;
  1843. begin
  1844. Result:=AdjustLineBreaks(S,DefaultTextLineBreakStyle);
  1845. end;
  1846. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  1847. var
  1848. I,L: Longint;
  1849. Res : String;
  1850. Procedure Add(C : Char);
  1851. begin
  1852. Res:=Res+C;
  1853. end;
  1854. begin
  1855. I:=0;
  1856. L:=Length(S);
  1857. Result:='';
  1858. While (I<=L) do
  1859. case S[I] of
  1860. #10: begin
  1861. if Style in [tlbsCRLF,tlbsCR] then
  1862. Add(#13);
  1863. if Style=tlbsCRLF then
  1864. Add(#10);
  1865. Inc(I);
  1866. end;
  1867. #13: begin
  1868. if Style=tlbsCRLF then
  1869. Add(#13);
  1870. Add(#10);
  1871. Inc(I);
  1872. if S[I]=#10 then
  1873. Inc(I);
  1874. end;
  1875. else
  1876. Add(S[i]);
  1877. Inc(I);
  1878. end;
  1879. Result:=Res;
  1880. end;
  1881. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  1882. const
  1883. Quotes = ['''', '"'];
  1884. Var
  1885. L : String;
  1886. C,LQ,BC : Char;
  1887. P,BLen,Len : Integer;
  1888. HB,IBC : Boolean;
  1889. begin
  1890. Result:='';
  1891. L:=Line;
  1892. Blen:=Length(BreakStr);
  1893. If (BLen>0) then
  1894. BC:=BreakStr[1]
  1895. else
  1896. BC:=#0;
  1897. Len:=Length(L);
  1898. While (Len>0) do
  1899. begin
  1900. P:=1;
  1901. LQ:=#0;
  1902. HB:=False;
  1903. IBC:=False;
  1904. While ((P<=Len) and ((P<=MaxCol) or not IBC)) and ((LQ<>#0) or Not HB) do
  1905. begin
  1906. C:=L[P];
  1907. If (C=LQ) then
  1908. LQ:=#0
  1909. else If (C in Quotes) then
  1910. LQ:=C;
  1911. If (LQ<>#0) then
  1912. Inc(P)
  1913. else
  1914. begin
  1915. HB:=((C=BC) and (BreakStr=Copy(L,P,BLen)));
  1916. If HB then
  1917. Inc(P,Blen)
  1918. else
  1919. begin
  1920. If (P>=MaxCol) then
  1921. IBC:=CharInSet(C,BreakChars);
  1922. Inc(P);
  1923. end;
  1924. end;
  1925. // Writeln('"',C,'" : IBC : ',IBC,' HB : ',HB,' LQ : ',LQ,' P>MaxCol : ',P>MaxCol);
  1926. end;
  1927. Result:=Result+Copy(L,1,P-1);
  1928. Delete(L,1,P-1);
  1929. Len:=Length(L);
  1930. If (Len>0) and Not HB then
  1931. Result:=Result+BreakStr;
  1932. end;
  1933. end;
  1934. function WrapText(const Line: string; MaxCol: Integer): string;
  1935. begin
  1936. Result:=WrapText(Line,sLineBreak, [' ', '-', #9], MaxCol);
  1937. end;
  1938. function GetEnvironmentVariable(const EnvVar: String): String;
  1939. begin
  1940. if Assigned(OnGetEnvironmentVariable) then
  1941. Result:=OnGetEnvironmentVariable(EnvVar)
  1942. else
  1943. Result:='';
  1944. end;
  1945. function GetEnvironmentVariableCount: Integer;
  1946. begin
  1947. if Assigned(OnGetEnvironmentVariableCount) then
  1948. Result:=OnGetEnvironmentVariableCount()
  1949. else
  1950. Result:=0;
  1951. end;
  1952. function GetEnvironmentString(Index: Integer): String;
  1953. begin
  1954. if Assigned(OnGetEnvironmentString) then
  1955. Result:=OnGetEnvironmentString(Index)
  1956. else
  1957. Result:='';
  1958. end;
  1959. { Date/Time routines}
  1960. Function DoEncodeDate(Year, Month, Day: Word): longint;
  1961. Var
  1962. D : TDateTime;
  1963. begin
  1964. If TryEncodeDate(Year,Month,Day,D) then
  1965. Result:=Trunc(D)
  1966. else
  1967. Result:=0;
  1968. end;
  1969. function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime;
  1970. begin
  1971. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  1972. Result:=0;
  1973. end;
  1974. Function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  1975. Var
  1976. Y,M,D,h,n,s,z : Word;
  1977. begin
  1978. DecodeDate(Trunc(aDateTime),Y,M,D);
  1979. DecodeTime(Frac(aDateTime),H,N,S,Z);
  1980. Result:=TJSDate.New(Y,M,D,h,n,s,z);
  1981. end;
  1982. Function JSDatetoDateTime(ADate: TJSDate) : TDateTime;
  1983. begin
  1984. Result:=EncodeDate(ADate.FullYear,ADate.Month+1,ADate.Date) +
  1985. EncodeTime(ADate.Hours,ADate.Minutes,ADate.Seconds,ADate.Milliseconds);
  1986. end;
  1987. { ComposeDateTime converts a Date and a Time into one TDateTime }
  1988. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  1989. begin
  1990. if Date < 0 then
  1991. Result := trunc(Date) - Abs(frac(Time))
  1992. else
  1993. Result := trunc(Date) + Abs(frac(Time));
  1994. end;
  1995. Function TryEncodeDate(Year,Month,Day : Word; Out Date : TDateTime) : Boolean;
  1996. var
  1997. c, ya: LongWord;
  1998. begin
  1999. Result:=(Year>0) and (Year<10000) and
  2000. (Month >= 1) and (Month<=12) and
  2001. (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]);
  2002. If Result then
  2003. begin
  2004. if month > 2 then
  2005. Dec(Month,3)
  2006. else
  2007. begin
  2008. Inc(Month,9);
  2009. Dec(Year);
  2010. end;
  2011. c:= Year DIV 100;
  2012. ya:= Year - 100*c;
  2013. Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*LongWord(Month)+2) DIV 5 + LongWord(Day);
  2014. // Note that this line can't be part of the line above, since TDateTime is
  2015. // signed and c and ya are not
  2016. Date := Date - 693900;
  2017. end
  2018. end;
  2019. function TryEncodeTime(Hour, Min, Sec, MSec:word; Out Time : TDateTime) : boolean;
  2020. begin
  2021. Result:=(Hour<24) and (Min<60) and (Sec<60) and (MSec<1000);
  2022. If Result then
  2023. Time:=TDateTime(LongWord(Hour)*3600000+LongWord(Min)*60000+LongWord(Sec)*1000+MSec)/MSecsPerDay;
  2024. end;
  2025. { EncodeDate packs three variables Year, Month and Day into a
  2026. TDateTime value the result is the number of days since 12/30/1899 }
  2027. function EncodeDate(Year, Month, Day: word): TDateTime;
  2028. begin
  2029. If Not TryEncodeDate(Year,Month,Day,Result) then
  2030. Raise EConvertError.CreateFmt('%s-%s-%s is not a valid date specification',
  2031. [IntToStr(Year),IntToStr(Month),IntToStr(Day)]);
  2032. end;
  2033. { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into
  2034. a TDateTime value }
  2035. function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime;
  2036. begin
  2037. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2038. Raise EConvertError.CreateFmt('%s:%s:%s.%s is not a valid time specification',
  2039. [IntToStr(Hour),IntToStr(Minute),IntToStr(Second),IntToStr(MilliSecond)]);
  2040. end;
  2041. { DecodeDate unpacks the value Date into three values:
  2042. Year, Month and Day }
  2043. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  2044. var
  2045. ly,ld,lm,j : LongWord;
  2046. begin
  2047. if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0
  2048. begin
  2049. Year := 0;
  2050. Month := 0;
  2051. Day := 0;
  2052. end
  2053. else
  2054. begin
  2055. if Date>0 then
  2056. Date:=(Date+(1/(msecsperday*2)))
  2057. else
  2058. Date:=Date-(1/(msecsperday*2));
  2059. if Date>MaxDateTime then
  2060. Date:=MaxDateTime;
  2061. // Raise EConvertError.CreateFmt('%f is not a valid TDatetime encoding, maximum value is %f.',[Date,MaxDateTime]);
  2062. j := ((Trunc(Date) + 693900) SHL 2)-1;
  2063. ly:= j DIV 146097;
  2064. j:= j - 146097 * LongWord(ly);
  2065. ld := j SHR 2;
  2066. j:=(ld SHL 2 + 3) DIV 1461;
  2067. ld:= ((ld SHL 2) + 7 - 1461*j) SHR 2;
  2068. lm:=(5 * ld-3) DIV 153;
  2069. ld:= (5 * ld +2 - 153*lm) DIV 5;
  2070. ly:= 100 * LongWord(ly) + j;
  2071. if lm < 10 then
  2072. inc(lm,3)
  2073. else
  2074. begin
  2075. dec(lm,9);
  2076. inc(ly);
  2077. end;
  2078. year:=ly;
  2079. month:=lm;
  2080. day:=ld;
  2081. end;
  2082. end;
  2083. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  2084. begin
  2085. DecodeDate(DateTime,Year,Month,Day);
  2086. DOW:=DayOfWeek(DateTime);
  2087. Result:=IsLeapYear(Year);
  2088. end;
  2089. { DateTimeToTimeStamp converts DateTime to a TTimeStamp }
  2090. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  2091. Var
  2092. D : Double;
  2093. begin
  2094. D:=DateTime * Double(MSecsPerDay);
  2095. if D<0 then
  2096. D:=D-0.5
  2097. else
  2098. D:=D+0.5;
  2099. result.Time := Trunc(Abs(Trunc(D)) Mod MSecsPerDay);
  2100. result.Date := DateDelta + (Trunc(D) div MSecsPerDay);
  2101. end;
  2102. { TimeStampToDateTime converts TimeStamp to a TDateTime value }
  2103. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  2104. begin
  2105. Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time/MSecsPerDay)
  2106. end;
  2107. { MSecsToTimeStamp }
  2108. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  2109. begin
  2110. result.Date := Trunc(msecs/msecsperday);
  2111. msecs:= msecs-NativeInt(result.date)*msecsperday;
  2112. result.Time := Round(MSecs);
  2113. end;
  2114. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  2115. begin
  2116. result := TimeStamp.Time + (timestamp.date*msecsperday);
  2117. end ;
  2118. { DecodeTime unpacks Time into four values:
  2119. Hour, Minute, Second and MilliSecond }
  2120. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  2121. Var
  2122. l : LongWord;
  2123. begin
  2124. l := DateTimeToTimeStamp(Time).Time;
  2125. Hour := l div 3600000;
  2126. l := l mod 3600000;
  2127. Minute := l div 60000;
  2128. l := l mod 60000;
  2129. Second := l div 1000;
  2130. l := l mod 1000;
  2131. MilliSecond := l;
  2132. end;
  2133. { DateTimeToSystemTime converts DateTime value to SystemTime }
  2134. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  2135. begin
  2136. DecodeDateFully(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.DayOfWeek);
  2137. DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond);
  2138. Dec(SystemTime.DayOfWeek);
  2139. end ;
  2140. { SystemTimeToDateTime converts SystemTime to a TDateTime value }
  2141. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  2142. begin
  2143. result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day),
  2144. DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond));
  2145. end ;
  2146. function DayOfWeek(DateTime: TDateTime): integer;
  2147. begin
  2148. Result := 1 + ((Trunc(DateTime) - 1) mod 7);
  2149. If (Result<=0) then
  2150. Inc(Result,7);
  2151. end;
  2152. function Now: TDateTime;
  2153. begin
  2154. Result:=JSDateToDateTime(TJSDate.New());
  2155. end;
  2156. function Date: TDateTime;
  2157. begin
  2158. Result:=Trunc(Now);
  2159. end;
  2160. function Time: TDateTime;
  2161. begin
  2162. Result:=Now-Date;
  2163. end ;
  2164. { IncMonth increments DateTime with NumberOfMonths months,
  2165. NumberOfMonths can be less than zero }
  2166. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  2167. var
  2168. Year, Month, Day : word;
  2169. begin
  2170. DecodeDate(DateTime, Year, Month, Day);
  2171. IncAMonth(Year, Month, Day, NumberOfMonths);
  2172. result := ComposeDateTime(DoEncodeDate(Year, Month, Day), DateTime);
  2173. end ;
  2174. { IncAMonth is the same as IncMonth, but operates on decoded date }
  2175. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  2176. var
  2177. TempMonth, S: Integer;
  2178. begin
  2179. If NumberOfMonths>=0 then
  2180. s:=1
  2181. else
  2182. s:=-1;
  2183. inc(Year,(NumberOfMonths div 12));
  2184. TempMonth:=Month+(NumberOfMonths mod 12)-1;
  2185. if (TempMonth>11) or
  2186. (TempMonth<0) then
  2187. begin
  2188. Dec(TempMonth, S*12);
  2189. Inc(Year, S);
  2190. end;
  2191. Month:=TempMonth+1; { Months from 1 to 12 }
  2192. If (Day>MonthDays[IsLeapYear(Year)][Month]) then
  2193. Day:=MonthDays[IsLeapYear(Year)][Month];
  2194. end;
  2195. { IsLeapYear returns true if Year is a leap year }
  2196. function IsLeapYear(Year: Word): boolean;
  2197. begin
  2198. Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
  2199. end;
  2200. { DateToStr returns a string representation of Date using ShortDateFormat }
  2201. function DateToStr(Date: TDateTime): string;
  2202. begin
  2203. Result:=FormatDateTime('ddddd', Date);
  2204. end ;
  2205. { TimeToStr returns a string representation of Time using LongTimeFormat }
  2206. function TimeToStr(Time: TDateTime): string;
  2207. begin
  2208. Result:=FormatDateTime('tt',Time);
  2209. end ;
  2210. { DateTimeToStr returns a string representation of DateTime using LongDateTimeFormat }
  2211. Var
  2212. DateTimeToStrFormat : Array[Boolean] of string = ('c','f');
  2213. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  2214. begin
  2215. Result:=FormatDateTime(DateTimeToStrFormat[ForceTimeIfZero], DateTime)
  2216. end ;
  2217. { StrToDate converts the string S to a TDateTime value
  2218. if S does not represent a valid date value
  2219. an EConvertError will be raised }
  2220. function IntStrToDate(Out ErrorMsg : String; const S: String; const useformat : string; separator : char): TDateTime;
  2221. Const
  2222. WhiteSpace = ' '#8#9#10#12#13;
  2223. Digits = '0123456789';
  2224. procedure FixErrorMsg(const errmarg : String);
  2225. begin
  2226. ErrorMsg:=Format(SInvalidDateFormat,[errmarg]);
  2227. end;
  2228. var
  2229. df:string;
  2230. d,m,y,ly,ld,lm:word;
  2231. n,i,len:longint;
  2232. c: integer;
  2233. dp,mp,yp,which : Byte;
  2234. s1:string;
  2235. values: array of integer;
  2236. YearMoreThenTwoDigits : boolean;
  2237. begin
  2238. SetLength(values,4);
  2239. Result:=0;
  2240. Len:=Length(S);
  2241. ErrorMsg:='';
  2242. While (Len>0) and (Pos(S[Len],WhiteSpace)>0) do
  2243. Dec(len);
  2244. if (Len=0) then
  2245. begin
  2246. FixErrorMsg(S);
  2247. exit;
  2248. end;
  2249. YearMoreThenTwoDigits := False;
  2250. if separator = #0 then
  2251. if (DateSeparator<>#0) then
  2252. separator := DateSeparator
  2253. else
  2254. separator:='-';
  2255. // Writeln('Separator: ',Separator);
  2256. df := UpperCase(useFormat);
  2257. { Determine order of D,M,Y }
  2258. yp:=0;
  2259. mp:=0;
  2260. dp:=0;
  2261. Which:=0;
  2262. i:=0;
  2263. while (i<Length(df)) and (Which<3) do
  2264. begin
  2265. inc(i);
  2266. Case df[i] of
  2267. 'Y' :
  2268. if yp=0 then
  2269. begin
  2270. Inc(Which);
  2271. yp:=which;
  2272. end;
  2273. 'M' :
  2274. if mp=0 then
  2275. begin
  2276. Inc(Which);
  2277. mp:=which;
  2278. end;
  2279. 'D' :
  2280. if dp=0 then
  2281. begin
  2282. Inc(Which);
  2283. dp:=which;
  2284. end;
  2285. end;
  2286. end;
  2287. // Writeln('YP: ',Yp,', MP: ',Mp,', DP: ',DP);
  2288. for i := 1 to 3 do
  2289. values[i] := 0;
  2290. s1 := '';
  2291. n := 0;
  2292. for i := 1 to len do
  2293. begin
  2294. if Pos(s[i],Digits)>0 then
  2295. s1 := s1 + s[i];
  2296. { space can be part of the shortdateformat, and is defaultly in slovak
  2297. windows, therefor it shouldn't be taken as separator (unless so specified)
  2298. and ignored }
  2299. if (Separator <> ' ') and (s[i] = ' ') then
  2300. Continue;
  2301. if (s[i] = separator) or ((i = len) and (Pos(s[i],Digits)>0)) then
  2302. begin
  2303. inc(n);
  2304. if n>3 then
  2305. begin
  2306. // Writeln('More than 3 separators');
  2307. FixErrorMsg(S);
  2308. exit;
  2309. end;
  2310. // Check if the year has more then two digits (if n=yp, then we are evaluating the year.)
  2311. if (n=yp) and (length(s1)>2) then YearMoreThenTwoDigits := True;
  2312. val(s1, values[n], c);
  2313. if c<>0 then
  2314. begin
  2315. // Writeln('S1 not a number ',S1);
  2316. FixErrorMsg(s);
  2317. Exit;
  2318. end;
  2319. s1 := '';
  2320. end
  2321. else if (Pos(s[i],Digits)=0) then
  2322. begin
  2323. // Writeln('Not a number at pos ',I,' ',S[i]);
  2324. FixErrorMsg(s);
  2325. Exit;
  2326. end;
  2327. end ;
  2328. // Writeln('Which : ',Which,' N : ',N);
  2329. if (Which<3) and (N>Which) then
  2330. begin
  2331. FixErrorMsg(s);
  2332. Exit;
  2333. end;
  2334. // Fill in values.
  2335. DecodeDate(Date,Ly,LM,LD);
  2336. If N=3 then
  2337. begin
  2338. y:=values[yp];
  2339. m:=values[mp];
  2340. d:=values[dp];
  2341. end
  2342. Else
  2343. begin
  2344. Y:=ly;
  2345. If n<2 then
  2346. begin
  2347. d:=values[1];
  2348. m := LM;
  2349. end
  2350. else
  2351. If dp<mp then
  2352. begin
  2353. d:=values[1];
  2354. m:=values[2];
  2355. end
  2356. else
  2357. begin
  2358. d:=values[2];
  2359. m:=values[1];
  2360. end;
  2361. end;
  2362. if (y >= 0) and (y < 100) and not YearMoreThenTwoDigits then
  2363. begin
  2364. ly := ly - TwoDigitYearCenturyWindow;
  2365. Inc(Y, ly div 100 * 100);
  2366. if (TwoDigitYearCenturyWindow > 0) and (Y < ly) then
  2367. Inc(Y, 100);
  2368. end;
  2369. if not TryEncodeDate(y, m, d, result) then
  2370. errormsg:=SErrInvalidDate;
  2371. end;
  2372. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  2373. Var
  2374. MSg : String;
  2375. begin
  2376. Result:=IntStrToDate(Msg,S,useFormat,Separator);
  2377. If (Msg<>'') then
  2378. Raise EConvertError.Create(Msg);
  2379. end;
  2380. function StrToDate(const S: String; separator : char): TDateTime;
  2381. begin
  2382. result := StrToDate(S,ShortDateFormat,separator)
  2383. end;
  2384. function StrToDate(const S: String): TDateTime;
  2385. begin
  2386. result := StrToDate(S,ShortDateFormat,#0);
  2387. end;
  2388. { StrToTime converts the string S to a TDateTime value
  2389. if S does not represent a valid time value an
  2390. EConvertError will be raised }
  2391. function IntStrToTime(Out ErrorMsg : String; const S: String; Len : integer; separator : char): TDateTime;
  2392. const
  2393. AMPM_None = 0;
  2394. AMPM_AM = 1;
  2395. AMPM_PM = 2;
  2396. tiHour = 0;
  2397. tiMin = 1;
  2398. tiSec = 2;
  2399. tiMSec = 3;
  2400. type
  2401. TTimeValues = array of Word;
  2402. var
  2403. AmPm: integer;
  2404. TimeValues: TTimeValues;
  2405. function SplitElements(out TimeValues: TTimeValues; out AmPm: Integer): Boolean;
  2406. //Strict version. It does not allow #32 as Separator, it will treat it as whitespace always
  2407. const
  2408. Digits = '0123456789';
  2409. var
  2410. Cur, Offset, ElemLen, Err, TimeIndex, FirstSignificantDigit: Integer;
  2411. Value: Integer;
  2412. DigitPending, MSecPending: Boolean;
  2413. AmPmStr: String;
  2414. CurChar: Char;
  2415. I : Integer;
  2416. allowedchars : string;
  2417. begin
  2418. Result := False;
  2419. AmPm := AMPM_None; //No Am or PM in string found yet
  2420. MSecPending := False;
  2421. TimeIndex := 0; //indicating which TTimeValue must be filled next
  2422. For I:=tiHour to tiMSec do
  2423. TimeValues[i]:=0;
  2424. Cur := 1;
  2425. //skip leading blanks
  2426. While (Cur < Len) and (S[Cur] =#32) do Inc(Cur);
  2427. Offset := Cur;
  2428. //First non-blank cannot be Separator or DecimalSeparator
  2429. if (Cur > Len - 1) or (S[Cur] = Separator) or (S[Cur] = Decimalseparator) then
  2430. begin
  2431. // Writeln('Error in sep S[Cur]',S[Cur],' ',separator,' ',GetDecimalSeparator);
  2432. Exit;
  2433. end;
  2434. DigitPending := (Pos(S[Cur],Digits)>0);
  2435. While (Cur <= Len) do
  2436. begin
  2437. //writeln;
  2438. // writeln('Main While loop: Cur = ',Cur,' S[Cur] = "',S[Cur],'" Len = ',Len,' separator : ',Separator);
  2439. CurChar := S[Cur];
  2440. if Pos(CurChar,Digits)>0 then
  2441. begin//Digits
  2442. //HH, MM, SS, or Msec?
  2443. // writeln('Digit: ', CurChar);
  2444. //Digits are only allowed after starting Am/PM or at beginning of string or after Separator
  2445. //and TimeIndex must be <= tiMSec
  2446. //Uncomment "or (#32 = Separator)" and it will allllow #32 as separator
  2447. if (not (DigitPending {or (#32 = Separator)})) or (TimeIndex > tiMSec) then
  2448. begin
  2449. // Writeln('DigitPending',ElemLen);
  2450. Exit;
  2451. end;
  2452. OffSet := Cur;
  2453. if (CurChar <> '0') then FirstSignificantDigit := OffSet else FirstSignificantDigit := -1;
  2454. while (Cur < Len) and (Pos(S[Cur + 1],Digits)>0) do
  2455. begin
  2456. //Mark first Digit that is not '0'
  2457. if (FirstSignificantDigit = -1) and (S[Cur] <> '0') then FirstSignificantDigit := Cur;
  2458. Inc(Cur);
  2459. end;
  2460. if (FirstSignificantDigit = -1) then FirstSignificantDigit := Cur;
  2461. ElemLen := 1+ Cur - FirstSignificantDigit;
  2462. // writeln(' S[FirstSignificantDigit] = ',S[FirstSignificantDigit], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[Offset], ElemLen);
  2463. // writeln(' Cur = ',Cur);
  2464. //this way we know that Val() will never overflow Value !
  2465. if (ElemLen <= 2) or ((ElemLen <= 3) and (TimeIndex = tiMSec) ) then
  2466. begin
  2467. Val(Copy(S,FirstSignificantDigit, ElemLen), Value, Err);
  2468. // writeln(' Value = ',Value,' HH = ',TimeValues[0],' MM = ',TimeValues[1],' SS = ',TimeValues[2],' MSec = ',Timevalues[3]);
  2469. //This is safe now, because we know Value < High(Word)
  2470. TimeValues[TimeIndex] := Value;
  2471. Inc(TimeIndex);
  2472. DigitPending := False;
  2473. end
  2474. else
  2475. begin
  2476. // Writeln('Wrong elemlen: ',ElemLen, ' timeIndex: ',timeindex);
  2477. Exit; //Value to big, so it must be a wrong timestring
  2478. end;
  2479. end//Digits
  2480. else if (CurChar = #32) then
  2481. begin
  2482. //writeln('#32');
  2483. //just skip, but we must adress this, or it will be parsed by either AM/PM or Separator
  2484. end
  2485. else if (CurChar = Separator) then
  2486. begin
  2487. // writeln('Separator ',Separator);
  2488. if DigitPending or (TimeIndex > tiSec) then
  2489. begin
  2490. // Writeln ('DigitPending ',DigitPending,' or (TimeIndex',Timeindex,' > tiSec,', tiSec,')');
  2491. Exit;
  2492. end;
  2493. DigitPending := True;
  2494. MSecPending := False;
  2495. end
  2496. else if (CurChar = DecimalSeparator) then
  2497. begin
  2498. //writeln('DecimalSeparator');
  2499. if DigitPending or MSecPending or (TimeIndex <> tiMSec) then
  2500. begin
  2501. // Writeln('DigitPending ',DigitPending,' or MSecPending ',MSecPending,' (',TimeIndex,',Timeindex, >', tiMSec,' tiSec)');
  2502. Exit;
  2503. end;
  2504. DigitPending := True;
  2505. MSecPending := True;
  2506. end
  2507. else
  2508. begin//AM/PM?
  2509. //None of the above, so this char _must_ be the start of AM/PM string
  2510. //If we already have found AM/PM or we expect a digit then then timestring must be wrong at this point
  2511. //writeln('AM/PM?');
  2512. if (AmPm <> AMPM_None) or DigitPending then
  2513. begin
  2514. // Writeln('AmPm <> AMPM_None) or DigitPending');
  2515. Exit;
  2516. end;
  2517. OffSet := Cur;
  2518. allowedchars:=DecimalSeparator+' ';
  2519. if Separator<>#0 then
  2520. allowedchars:=allowedchars+Separator;
  2521. while (Cur < Len -1) and (Pos(S[Cur + 1],AllowedChars)=0)
  2522. and (Pos(S[Cur + 1],Digits)=0) do Inc(Cur);
  2523. ElemLen := 1 + Cur - OffSet;
  2524. // writeln(' S[Offset] = ',S[1+Offset], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[1+Offset], ElemLen);
  2525. // writeln(' Cur = ',Cur, 'S =',S);
  2526. AmPmStr := Copy(S,1+OffSet, ElemLen);
  2527. // writeln('AmPmStr = ',ampmstr,' (',length(ampmstr),')');
  2528. //We must compare to TimeAMString before hardcoded 'AM' for delphi compatibility
  2529. //Also it is perfectly legal, though insane to have TimeAMString = 'PM' and vice versa
  2530. if (CompareText(AmPmStr, TimeAMString) = 0) then AmPm := AMPM_AM
  2531. else if (CompareText(AmPmStr, TimePMString) = 0) then AmPm := AMPM_PM
  2532. else if (CompareText(AmPmStr, 'AM') = 0) then AmPm := AMPM_AM
  2533. else if (CompareText(AmPmStr, 'PM') = 0) then AmPm := AMPM_PM
  2534. else
  2535. begin
  2536. // Writeln('No timestring ',AmPmStr);
  2537. Exit; //If text does not match any of these, timestring must be wrong;
  2538. end;
  2539. //if AM/PM is at beginning of string, then a digit is mandatory after it
  2540. if (TimeIndex = tiHour) then
  2541. begin
  2542. DigitPending := True;
  2543. end
  2544. //otherwise, no more TimeValues allowed after this
  2545. else
  2546. begin
  2547. TimeIndex := tiMSec + 1;
  2548. DigitPending := False;
  2549. end;
  2550. end;//AM/PM
  2551. Inc(Cur)
  2552. end;//while
  2553. //If we arrive here, parsing the elements has been successfull
  2554. //if not at least Hours specified then input is not valid
  2555. //when am/pm is specified Hour must be <= 12 and not 0
  2556. if (TimeIndex = tiHour) or ((AmPm <> AMPM_None) and ((TimeValues[tiHour] > 12) or (TimeValues[tiHour] = 0))) or DigitPending then
  2557. Exit;
  2558. Result := True;
  2559. end;
  2560. begin
  2561. setlength(timevalues,4);
  2562. if separator = #0 then
  2563. if (TimeSeparator<>#0) then
  2564. separator := TimeSeparator
  2565. else
  2566. separator:=':';
  2567. AmPm := AMPM_None;
  2568. if not SplitElements(TimeValues, AmPm) then
  2569. begin
  2570. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2571. Exit;
  2572. end;
  2573. if (AmPm=AMPM_PM) and (TimeValues[tiHour]<>12) then Inc(TimeValues[tiHour], 12)
  2574. else if (AmPm=AMPM_AM) and (TimeValues[tiHour]=12) then TimeValues[tiHour]:=0;
  2575. // Writeln( TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec]);
  2576. if not TryEncodeTime(TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec], result) Then
  2577. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2578. end ;
  2579. function StrToTime(const s: String; separator : char): TDateTime;
  2580. Var
  2581. Msg : String;
  2582. begin
  2583. Result:=IntStrToTime(Msg,S,Length(S),Separator);
  2584. If (Msg<>'') then
  2585. Raise EConvertError.Create(Msg);
  2586. end;
  2587. function StrToTime(const s: String): TDateTime;
  2588. begin
  2589. result:= StrToTime(s, TimeSeparator);
  2590. end;
  2591. { StrToDateTime converts the string S to a TDateTime value
  2592. if S does not represent a valid date and/or time value
  2593. an EConvertError will be raised }
  2594. function SplitDateTimeStr(DateTimeStr: String; out DateStr, TimeStr: String): Integer;
  2595. { Helper function for StrToDateTime
  2596. Pre-condition
  2597. Date is before Time
  2598. If either Date or Time is omitted then see what fits best, a time or a date (issue #0020522)
  2599. Date and Time are separated by whitespace (space Tab, Linefeed or carriage return)
  2600. FS.DateSeparator can be the same as FS.TimeSeparator (issue #0020522)
  2601. If they are both #32 and TrimWhite(DateTimeStr) contains a #32 a date is assumed.
  2602. Post-condition
  2603. DateStr holds date as string or is empty
  2604. TimeStr holds time as string or is empty
  2605. Result = number of strings returned, 0 = error
  2606. }
  2607. const
  2608. WhiteSpace = #9#10#13#32;
  2609. var
  2610. p: Integer;
  2611. DummyDT: TDateTime;
  2612. begin
  2613. Result := 0;
  2614. DateStr := '';
  2615. TimeStr := '';
  2616. DateTimeStr := Trim(DateTimeStr);
  2617. if Length(DateTimeStr) = 0 then exit;
  2618. if (DateSeparator = #32) and (TimeSeparator = #32) and (Pos(#32, DateTimeStr) > 0) then
  2619. begin
  2620. DateStr:=DateTimeStr;
  2621. {
  2622. Assume a date: dd [mm [yy]].
  2623. Really fancy would be counting the number of whitespace occurrences and decide
  2624. and split accordingly
  2625. }
  2626. Exit(1);
  2627. end;
  2628. p:=1;
  2629. //find separator
  2630. if (DateSeparator<>#32) then
  2631. begin
  2632. while (p<Length(DateTimeStr)) and (not (Pos(DateTimeStr[p+1],WhiteSpace)>0)) do
  2633. Inc(p);
  2634. end
  2635. else
  2636. begin
  2637. p:=Pos(TimeSeparator, DateTimeStr);
  2638. if (p<>0) then
  2639. repeat
  2640. Dec(p);
  2641. until (p=0) or (Pos(DateTimeStr[p],WhiteSpace)>0);
  2642. end;
  2643. //Always fill DateStr, it eases the algorithm later
  2644. if (p=0) then
  2645. p:=Length(DateTimeStr);
  2646. DateStr:=Copy(DateTimeStr,1,p);
  2647. TimeStr:=Trim(Copy(DateTimeStr,p+1,100));
  2648. if (Length(TimeStr)<>0) then
  2649. Result:=2
  2650. else
  2651. begin
  2652. Result:=1; //found 1 string
  2653. // 2 cases when DateTimeStr only contains a time:
  2654. // Date/time separator differ, and string contains a timeseparator
  2655. // Date/time separators are equal, but transformation to date fails.
  2656. if ((DateSeparator<>TimeSeparator) and (Pos(TimeSeparator,DateStr) > 0))
  2657. or ((DateSeparator=TimeSeparator) and (not TryStrToDate(DateStr, DummyDT))) then
  2658. begin
  2659. TimeStr := DateStr;
  2660. DateStr := '';
  2661. end;
  2662. end;
  2663. end;
  2664. function StrToDateTime(const s: String): TDateTime;
  2665. var
  2666. TimeStr, DateStr: String;
  2667. PartsFound: Integer;
  2668. begin
  2669. PartsFound := SplitDateTimeStr(S, DateStr, TimeStr);
  2670. case PartsFound of
  2671. 0: Result:=StrToDate('');
  2672. 1: if (Length(DateStr) > 0) then
  2673. Result := StrToDate(DateStr,ShortDateFormat,DateSeparator)
  2674. else
  2675. Result := StrToTime(TimeStr);
  2676. 2: Result := ComposeDateTime(StrTodate(DateStr,ShortDateFormat,DateSeparator),
  2677. StrToTime(TimeStr));
  2678. end;
  2679. end;
  2680. Function FormatDateTime(const FormatStr: string; const DateTime: TDateTime) : String;
  2681. procedure StoreStr(APos,Len: Integer);
  2682. begin
  2683. // Writeln('StoreStr: ',Result,'+',Copy(FormatStr,APos,Len));
  2684. Result:=Result+Copy(FormatStr,APos,Len);
  2685. end;
  2686. procedure StoreString(const AStr: string);
  2687. begin
  2688. // Writeln('StoreString: ',Result,'+',AStr);
  2689. Result:=Result+AStr;
  2690. end;
  2691. procedure StoreInt(Value, Digits: Integer);
  2692. var
  2693. S: string;
  2694. begin
  2695. S:=IntToStr(Value);
  2696. While (Length(S)<Digits) do
  2697. S:='0'+S;
  2698. StoreString(S);
  2699. end;
  2700. var
  2701. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  2702. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  2703. var
  2704. Token, lastformattoken, prevlasttoken: char;
  2705. Count: integer;
  2706. Clock12: boolean;
  2707. tmp: integer;
  2708. isInterval: Boolean;
  2709. P,FormatCurrent,FormatEnd : Integer;
  2710. begin
  2711. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  2712. Exit;
  2713. FormatCurrent := 1;
  2714. FormatEnd := Length(FormatStr);
  2715. Clock12 := false;
  2716. isInterval := false;
  2717. // look for unquoted 12-hour clock token
  2718. P:=1;
  2719. while P<=FormatEnd do
  2720. begin
  2721. Token := FormatStr[P];
  2722. case Token of
  2723. '''', '"':
  2724. begin
  2725. Inc(P);
  2726. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2727. Inc(P);
  2728. end;
  2729. 'A', 'a':
  2730. begin
  2731. if (CompareText(Copy(FormatStr,P,3),'A/P')=0) or
  2732. (CompareText(Copy(FormatStr,P,4),'AMPM')=0) or
  2733. (CompareText(Copy(FormatStr,P,5),'AM/PM')=0) then
  2734. begin
  2735. Clock12 := true;
  2736. break;
  2737. end;
  2738. end;
  2739. end; // case
  2740. Inc(P);
  2741. end ;
  2742. token := #255;
  2743. lastformattoken := ' ';
  2744. prevlasttoken := 'H';
  2745. while FormatCurrent <= FormatEnd do
  2746. begin
  2747. Token := UpperCase(FormatStr[FormatCurrent])[1];
  2748. // Writeln('Treating token at pos ',FormatCurrent,', : ',Token,' (',FormatStr,')');
  2749. Count := 1;
  2750. P := FormatCurrent + 1;
  2751. case Token of
  2752. '''', '"':
  2753. begin
  2754. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2755. Inc(P);
  2756. Inc(P);
  2757. Count := P - FormatCurrent;
  2758. StoreStr(FormatCurrent + 1, Count - 2);
  2759. end ;
  2760. 'A':
  2761. begin
  2762. if CompareText(Copy(FormatStr,FormatCurrent,4), 'AMPM') = 0 then
  2763. begin
  2764. Count := 4;
  2765. if Hour < 12 then
  2766. StoreString(TimeAMString)
  2767. else
  2768. StoreString(TimePMString);
  2769. end
  2770. else if CompareText(Copy(FormatStr,FormatCurrent,5), 'AM/PM') = 0 then
  2771. begin
  2772. Count := 5;
  2773. if Hour < 12 then StoreStr(FormatCurrent, 2)
  2774. else StoreStr(FormatCurrent+3, 2);
  2775. end
  2776. else if CompareText(Copy(FormatStr,FormatCurrent,3), 'A/P') = 0 then
  2777. begin
  2778. Count := 3;
  2779. if Hour < 12 then StoreStr(FormatCurrent, 1)
  2780. else StoreStr(FormatCurrent+2, 1);
  2781. end
  2782. else
  2783. raise EConvertError.Create('Illegal character in format string');
  2784. end ;
  2785. '/':
  2786. begin
  2787. // Writeln('Detected date separator');
  2788. StoreString(DateSeparator);
  2789. end;
  2790. ':': StoreString(TimeSeparator);
  2791. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' :
  2792. begin
  2793. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2794. while (P <= FormatEnd) and (UpperCase(FormatStr[P]) = Token) do
  2795. Inc(P);
  2796. Count := P - FormatCurrent;
  2797. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2798. case Token of
  2799. ' ': StoreStr(FormatCurrent, Count);
  2800. 'Y': begin
  2801. if Count > 2 then
  2802. StoreInt(Year, 4)
  2803. else
  2804. StoreInt(Year mod 100, 2);
  2805. end;
  2806. 'M': begin
  2807. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  2808. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2809. else
  2810. if (lastformattoken = 'H') or TimeFlag then
  2811. begin
  2812. if Count = 1 then
  2813. StoreInt(Minute, 0)
  2814. else
  2815. StoreInt(Minute, 2);
  2816. end
  2817. else
  2818. begin
  2819. case Count of
  2820. 1: StoreInt(Month, 0);
  2821. 2: StoreInt(Month, 2);
  2822. 3: StoreString(ShortMonthNames[Month]);
  2823. else
  2824. StoreString(LongMonthNames[Month]);
  2825. end;
  2826. end;
  2827. end;
  2828. 'D': begin
  2829. case Count of
  2830. 1: StoreInt(Day, 0);
  2831. 2: StoreInt(Day, 2);
  2832. 3: StoreString(ShortDayNames[DayOfWeek]);
  2833. 4: StoreString(LongDayNames[DayOfWeek]);
  2834. 5: StoreFormat(ShortDateFormat, Nesting+1, False);
  2835. else
  2836. StoreFormat(LongDateFormat, Nesting+1, False);
  2837. end ;
  2838. end ;
  2839. 'H':
  2840. if isInterval then
  2841. StoreInt(Hour + trunc(abs(DateTime))*24, 0)
  2842. else
  2843. if Clock12 then
  2844. begin
  2845. tmp := hour mod 12;
  2846. if tmp=0 then tmp:=12;
  2847. if Count = 1 then
  2848. StoreInt(tmp, 0)
  2849. else
  2850. StoreInt(tmp, 2);
  2851. end
  2852. else begin
  2853. if Count = 1 then
  2854. StoreInt(Hour, 0)
  2855. else
  2856. StoreInt(Hour, 2);
  2857. end;
  2858. 'N': if isInterval then
  2859. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2860. else
  2861. if Count = 1 then
  2862. StoreInt(Minute, 0)
  2863. else
  2864. StoreInt(Minute, 2);
  2865. 'S': if isInterval then
  2866. StoreInt(Second + (Minute + (Hour + trunc(abs(DateTime))*24)*60)*60, 0)
  2867. else
  2868. if Count = 1 then
  2869. StoreInt(Second, 0)
  2870. else
  2871. StoreInt(Second, 2);
  2872. 'Z': if Count = 1 then
  2873. StoreInt(MilliSecond, 0)
  2874. else
  2875. StoreInt(MilliSecond, 3);
  2876. 'T': if Count = 1 then
  2877. StoreFormat(ShortTimeFormat, Nesting+1, True)
  2878. else
  2879. StoreFormat(LongTimeFormat, Nesting+1, True);
  2880. 'C': begin
  2881. StoreFormat(ShortDateFormat, Nesting+1, False);
  2882. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  2883. begin
  2884. StoreString(' ');
  2885. StoreFormat(LongTimeFormat, Nesting+1, True);
  2886. end;
  2887. end;
  2888. 'F': begin
  2889. StoreFormat(ShortDateFormat, Nesting+1, False);
  2890. StoreString(' ');
  2891. StoreFormat(LongTimeFormat, Nesting+1, True);
  2892. end;
  2893. end;
  2894. prevlasttoken := lastformattoken;
  2895. lastformattoken := token;
  2896. end;
  2897. else
  2898. StoreString(Token);
  2899. end ;
  2900. Inc(FormatCurrent, Count);
  2901. end;
  2902. end;
  2903. begin
  2904. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  2905. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  2906. // Writeln(DateTime,'->',Year,',', Month, ',',Day, ',',DayOfWeek,',',Hour, ',',Minute, ',',Second, ',',MilliSecond);
  2907. if FormatStr <> '' then
  2908. StoreFormat(FormatStr, 0, False)
  2909. else
  2910. StoreFormat('C', 0, False);
  2911. end ;
  2912. function CurrentYear: Word;
  2913. begin
  2914. Result:=TJSDate.New().FullYear;
  2915. end;
  2916. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  2917. begin
  2918. Result:=TryStrToDate(S,Value,ShortDateFormat,#0);
  2919. end;
  2920. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  2921. begin
  2922. Result:=TryStrToDate(S,Value,ShortDateFormat,Separator);
  2923. end;
  2924. function TryStrToDate(const S: String; out Value: TDateTime;
  2925. const useformat : string; separator : char = #0): Boolean;
  2926. Var
  2927. Msg : String;
  2928. begin
  2929. Result:=Length(S)<>0;
  2930. If Result then
  2931. begin
  2932. Value:=IntStrToDate(Msg,S,useformat,Separator);
  2933. Result:=(Msg='');
  2934. end;
  2935. end;
  2936. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  2937. Var
  2938. Msg : String;
  2939. begin
  2940. Result:=Length(S)<>0;
  2941. If Result then
  2942. begin
  2943. Value:=IntStrToTime(Msg,S,Length(S),Separator);
  2944. Result:=(Msg='');
  2945. end;
  2946. end;
  2947. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  2948. begin
  2949. result:=TryStrToTime(S,Value,#0);
  2950. end;
  2951. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  2952. var
  2953. I: integer;
  2954. dtdate, dttime :TDateTime;
  2955. begin
  2956. result:=false;
  2957. I:=Pos(TimeSeparator,S);
  2958. If (I>0) then
  2959. begin
  2960. While (I>0) and (S[I]<>' ') do
  2961. Dec(I);
  2962. If I>0 then
  2963. begin
  2964. if not TryStrToDate(Copy(S,1,I-1),dtdate) then
  2965. exit;
  2966. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime) then
  2967. exit;
  2968. Value:=ComposeDateTime(dtdate,dttime);
  2969. result:=true;
  2970. end
  2971. else
  2972. result:=TryStrToTime(s,Value);
  2973. end
  2974. else
  2975. result:=TryStrToDate(s,Value);
  2976. end;
  2977. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  2978. begin
  2979. result := StrToDateDef(S,DefValue,#0);
  2980. end;
  2981. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  2982. begin
  2983. result := StrToTimeDef(S,DefValue,#0);
  2984. end;
  2985. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  2986. begin
  2987. if not TryStrToDateTime(s,Result) Then
  2988. result:=defvalue;
  2989. end;
  2990. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  2991. begin
  2992. if not TryStrToDate(s,Result, separator) Then
  2993. result:=defvalue;
  2994. end;
  2995. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  2996. begin
  2997. if not TryStrToTime(s,Result, separator) Then
  2998. result:=defvalue;
  2999. end;
  3000. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);
  3001. begin
  3002. dati:= ComposeDateTime(dati, newtime);
  3003. end;
  3004. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  3005. var
  3006. tmp : TDateTime;
  3007. begin
  3008. tmp:=NewDate;
  3009. ReplaceTime(tmp,DateTime);
  3010. DateTime:=tmp;
  3011. end;
  3012. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  3013. begin
  3014. If (Value<MinDateTime) or (Value>MaxDateTime) then
  3015. Raise EConvertError.CreateFmt (SInvalidDateTime,[FloatToStr(Value)]);
  3016. Result:=Value;
  3017. end;
  3018. function FloattoCurr(const Value: Extended): Currency;
  3019. begin
  3020. if not TryFloatToCurr(Value, Result) then
  3021. Raise EConvertError.CreateFmt(SInvalidCurrency, [FloatToStr(Value)]);
  3022. end;
  3023. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  3024. begin
  3025. Result:=(Value>=MinCurrency) and (Value<=MaxCurrency);
  3026. if Result then
  3027. AResult := Value;
  3028. end;
  3029. function CurrToStr(Value: Currency): string;
  3030. begin
  3031. Result:=FloatToStrF(Value,ffGeneral,-1,0);
  3032. end;
  3033. (*
  3034. function CurrToStr(Value: Currency; const FormatSettings: TFormatSettings): string;
  3035. begin
  3036. end;
  3037. *)
  3038. function StrToCurr(const S: string): Currency;
  3039. begin
  3040. if not TryStrToCurr(S,Result) then
  3041. Raise EConvertError.createfmt(SInvalidCurrency,[S]);
  3042. end;
  3043. (*
  3044. function StrToCurr(const S: string; const FormatSettings: TFormatSettings): Currency;
  3045. begin
  3046. end;
  3047. *)
  3048. function TryStrToCurr(const S: string; out Value: Currency): Boolean;
  3049. Var
  3050. D : Double;
  3051. begin
  3052. Result:=TryStrToFloat(S,D);
  3053. if Result then
  3054. Value:=D;
  3055. end;
  3056. (*
  3057. function TryStrToCurr(const S: string; out Value: Currency; const FormatSettings: TFormatSettings): Boolean;
  3058. begin
  3059. end;
  3060. *)
  3061. function StrToCurrDef(const S: string; Default: Currency): Currency;
  3062. Var
  3063. R : Currency;
  3064. begin
  3065. if TryStrToCurr(S,R) then
  3066. Result:=R
  3067. else
  3068. Result:=Default;
  3069. end;
  3070. (*
  3071. function StrToCurrDef(const S: string; Default: Currency; const FormatSettings: TFormatSettings): Currency;
  3072. begin
  3073. end;
  3074. *)
  3075. { ---------------------------------------------------------------------
  3076. Interface related
  3077. ---------------------------------------------------------------------}
  3078. function Supports(const Instance: IInterface; const AClass: TClass; out Obj
  3079. ): Boolean;
  3080. begin
  3081. Result := (Instance<>nil) and (Instance.QueryInterface(IObjectInstance,Obj)=S_OK)
  3082. and (TObject(Obj).InheritsFrom(AClass));
  3083. end;
  3084. function Supports(const Instance: IInterface; const IID: TGUID; out Intf
  3085. ): Boolean;
  3086. begin
  3087. Result:=(Instance<>nil) and (Instance.QueryInterface(IID,Intf)=S_OK);
  3088. end;
  3089. function Supports(const Instance: TObject; const IID: TGUID; out Intf
  3090. ): Boolean;
  3091. begin
  3092. Result:=(Instance<>nil) and Instance.GetInterface(IID,Intf);
  3093. end;
  3094. function Supports(const Instance: TObject; const IID: TGuidString; out Intf
  3095. ): Boolean;
  3096. begin
  3097. Result:=(Instance<>nil) and Instance.GetInterfaceByStr(IID,Intf);
  3098. end;
  3099. function Supports(const Instance: IInterface; const AClass: TClass): Boolean;
  3100. var
  3101. Temp: TObject;
  3102. begin
  3103. Result:=Supports(Instance,AClass,Temp);
  3104. end;
  3105. function Supports(const Instance: IInterface; const IID: TGUID): Boolean;
  3106. var
  3107. Temp: IInterface;
  3108. begin
  3109. Result:=Supports(Instance,IID,Temp);
  3110. end;
  3111. function Supports(const Instance: TObject; const IID: TGUID): Boolean;
  3112. var
  3113. Temp: TJSObject;
  3114. begin
  3115. Result:=Supports(Instance,IID,Temp);
  3116. asm
  3117. if (Temp && Temp.$kind==='com') Temp._Release();
  3118. end;
  3119. end;
  3120. function Supports(const Instance: TObject; const IID: TGuidString): Boolean;
  3121. var
  3122. Temp: TJSObject;
  3123. begin
  3124. Result:=Supports(Instance,IID,Temp);
  3125. asm
  3126. if (Temp && Temp.$kind==='com') Temp._Release();
  3127. end;
  3128. end;
  3129. function Supports(const AClass: TClass; const IID: TGUID): Boolean;
  3130. var
  3131. maps: JSValue;
  3132. begin
  3133. if AClass=nil then exit(false);
  3134. maps := TJSObject(AClass)['$intfmaps'];
  3135. if not maps then exit(false);
  3136. if TJSObject(maps)[GUIDToString(IID)] then exit(true);
  3137. Result:=false;
  3138. end;
  3139. function Supports(const AClass: TClass; const IID: TGuidString): Boolean;
  3140. var
  3141. maps: JSValue;
  3142. begin
  3143. if AClass=nil then exit(false);
  3144. maps := TJSObject(AClass)['$intfmaps'];
  3145. if not maps then exit(false);
  3146. if TJSObject(maps)[uppercase(IID)] then exit(true);
  3147. Result:=false;
  3148. end;
  3149. function TryStringToGUID(const s: string; out Guid: TGUID): Boolean;
  3150. var
  3151. re: TJSRegexp;
  3152. begin
  3153. if Length(s)<>38 then Exit(False);
  3154. re:=TJSRegexp.new('^\{[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}$');
  3155. Result:=re.test(s);
  3156. if not Result then
  3157. begin
  3158. Guid.D1:=0;
  3159. exit;
  3160. end;
  3161. asm
  3162. rtl.strToGUIDR(s,Guid.get());
  3163. end;
  3164. Result:=true;
  3165. end;
  3166. function StringToGUID(const S: string): TGUID;
  3167. begin
  3168. if not TryStringToGUID(S, Result) then
  3169. raise EConvertError.CreateFmt(SInvalidGUID, [S]);
  3170. end;
  3171. function GUIDToString(const guid: TGUID): string;
  3172. begin
  3173. Result:=System.GUIDToString(guid);
  3174. end;
  3175. function IsEqualGUID(const guid1, guid2: TGUID): Boolean;
  3176. var
  3177. i: integer;
  3178. begin
  3179. if (guid1.D1<>guid2.D1) or (guid1.D2<>guid2.D2) or (guid1.D3<>guid2.D3) then
  3180. exit(false);
  3181. for i:=0 to 7 do if guid1.D4[i]<>guid2.D4[i] then exit(false);
  3182. Result:=true;
  3183. end;
  3184. function GuidCase(const guid: TGUID; const List: array of TGuid): Integer;
  3185. begin
  3186. for Result := High(List) downto 0 do
  3187. if IsEqualGUID(guid, List[Result]) then
  3188. Exit;
  3189. Result := -1;
  3190. end;
  3191. { ---------------------------------------------------------------------
  3192. Integer/Ordinal related
  3193. ---------------------------------------------------------------------}
  3194. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  3195. Var
  3196. NI : NativeInt;
  3197. begin
  3198. Result:=TryStrToInt(S,NI);
  3199. if Result then
  3200. res:=NI;
  3201. end;
  3202. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  3203. Var
  3204. Radix : Integer = 10;
  3205. F,N : String;
  3206. J : JSValue;
  3207. begin
  3208. N:=S;
  3209. F:=Copy(N,1,1);
  3210. if (F='$') then
  3211. Radix:=16
  3212. else if (F='&') then
  3213. Radix:=8
  3214. else if (F='%') then
  3215. Radix:=2;
  3216. If Radix<>10 then
  3217. Delete(N,1,1);
  3218. J:=parseInt(N,Radix);
  3219. Result:=Not jsIsNan(j);
  3220. if Result then
  3221. res:=NativeInt(J);
  3222. end;
  3223. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  3224. Var
  3225. R : NativeInt;
  3226. begin
  3227. if TryStrToInt(S,R) then
  3228. Result:=R
  3229. else
  3230. Result:=aDef;
  3231. end;
  3232. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  3233. Var
  3234. R : NativeInt;
  3235. begin
  3236. if TryStrToInt(S,R) then
  3237. Result:=R
  3238. else
  3239. Result:=aDef;
  3240. end;
  3241. Function StrToInt(const S : String) : Integer;
  3242. Var
  3243. R : NativeInt;
  3244. begin
  3245. if not TryStrToInt(S,R) then
  3246. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3247. Result:=R;
  3248. end;
  3249. Function StrToNativeInt(const S : String) : NativeInt;
  3250. begin
  3251. if not TryStrToInt(S,Result) then
  3252. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3253. end;
  3254. Function StrToInt64(const S : String) : NativeLargeInt;
  3255. Var
  3256. N : NativeInt;
  3257. begin
  3258. if not TryStrToInt(S,N) then
  3259. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3260. Result:=N;
  3261. end;
  3262. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  3263. Var
  3264. R : nativeint;
  3265. begin
  3266. Result:=TryStrToInt(S,R);
  3267. If Result then
  3268. Res:=R;
  3269. end;
  3270. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  3271. begin
  3272. if TryStrToInt64(S,Result) then
  3273. Result:=ADefault;
  3274. end;
  3275. Function StrToQWord(const S : String) : NativeLargeUInt;
  3276. Var
  3277. N : NativeInt;
  3278. begin
  3279. if (not TryStrToInt(S,N)) or (N<0) then
  3280. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3281. Result:=N;
  3282. end;
  3283. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  3284. Var
  3285. R : nativeint;
  3286. begin
  3287. Result:=TryStrToInt(S,R) and (R>=0);
  3288. If Result then
  3289. Res:=R;
  3290. end;
  3291. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3292. begin
  3293. if Not TryStrToQword(S,Result) then
  3294. Result:=ADefault;
  3295. end;
  3296. Function StrToUInt64(const S : String) : NativeLargeUInt;
  3297. Var
  3298. N : NativeInt;
  3299. begin
  3300. if (not TryStrToInt(S,N)) or (N<0) then
  3301. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3302. Result:=N;
  3303. end;
  3304. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  3305. Var
  3306. R : nativeint;
  3307. begin
  3308. Result:=TryStrToInt(S,R) and (R>=0);
  3309. If Result then
  3310. Res:=R;
  3311. end;
  3312. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3313. begin
  3314. if Not TryStrToUInt64(S,Result) then
  3315. Result:=ADefault;
  3316. end;
  3317. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  3318. Var
  3319. R : nativeint;
  3320. begin
  3321. Result:=TryStrToInt(S,R) and (R>=0) and (R<=DWord($FFFFFFFF));
  3322. If Result then
  3323. Res:=R;
  3324. end;
  3325. Function StrToDWord(const S : String) : DWord;
  3326. begin
  3327. if not TryStrToDWord(S,Result) then
  3328. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3329. end;
  3330. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  3331. begin
  3332. if Not TryStrToDWord(S,Result) then
  3333. Result:=ADefault;
  3334. end;
  3335. function IntToHex(Value: NativeInt; Digits: integer): string;
  3336. const
  3337. HexDigits = '0123456789ABCDEF';
  3338. begin
  3339. If Digits=0 then
  3340. Digits:=1;
  3341. Result:='';
  3342. While Value>0 do
  3343. begin
  3344. result:=HexDigits[(value and 15)+1]+Result;
  3345. value := value shr 4;
  3346. end ;
  3347. while (Length(Result)<Digits) do
  3348. Result:='0'+Result;
  3349. end;
  3350. { TFormatSettings }
  3351. function TFormatSettings.GetCurrencyDecimals: Byte;
  3352. begin
  3353. Result:=Sysutils.CurrencyDecimals;
  3354. end;
  3355. function TFormatSettings.GetCurrencyFormat: Byte;
  3356. begin
  3357. Result:=Sysutils.CurrencyFormat;
  3358. end;
  3359. function TFormatSettings.GetCurrencyString: String;
  3360. begin
  3361. Result:=Sysutils.CurrencyString;
  3362. end;
  3363. function TFormatSettings.GetDateSeparator: char;
  3364. begin
  3365. Result := SysUtils.DateSeparator;
  3366. end;
  3367. function TFormatSettings.GetDecimalSeparator: string;
  3368. begin
  3369. Result := SysUtils.DecimalSeparator;
  3370. end;
  3371. function TFormatSettings.GetLongDateFormat: string;
  3372. begin
  3373. Result := SysUtils.LongDateFormat;
  3374. end;
  3375. function TFormatSettings.GetLongDayNames: TDayNames;
  3376. begin
  3377. Result:=Sysutils.LongDayNames;
  3378. end;
  3379. function TFormatSettings.GetLongMonthNames: TMonthNames;
  3380. begin
  3381. Result:=Sysutils.LongMonthNames;
  3382. end;
  3383. function TFormatSettings.GetLongTimeFormat: string;
  3384. begin
  3385. Result := SysUtils.LongTimeFormat;
  3386. end;
  3387. function TFormatSettings.GetNegCurrFormat: Byte;
  3388. begin
  3389. Result:=Sysutils.NegCurrFormat;
  3390. end;
  3391. function TFormatSettings.GetShortDateFormat: string;
  3392. begin
  3393. Result := SysUtils.ShortDateFormat;
  3394. end;
  3395. function TFormatSettings.GetShortDayNames: TDayNames;
  3396. begin
  3397. Result:=Sysutils.ShortDayNames;
  3398. end;
  3399. function TFormatSettings.GetShortMonthNames: TMonthNames;
  3400. begin
  3401. Result:=Sysutils.ShortMonthNames;
  3402. end;
  3403. function TFormatSettings.GetShortTimeFormat: string;
  3404. begin
  3405. Result := SysUtils.ShortTimeFormat;
  3406. end;
  3407. function TFormatSettings.GetThousandSeparator: string;
  3408. begin
  3409. Result := SysUtils.ThousandSeparator;
  3410. end;
  3411. function TFormatSettings.GetTimeAMString: string;
  3412. begin
  3413. Result := SysUtils.TimeAMString;
  3414. end;
  3415. function TFormatSettings.GetTimePMString: string;
  3416. begin
  3417. Result := SysUtils.TimePMString;
  3418. end;
  3419. function TFormatSettings.GetTimeSeparator: char;
  3420. begin
  3421. Result := SysUtils.TimeSeparator;
  3422. end;
  3423. procedure TFormatSettings.SetCurrencyFormat(AValue: Byte);
  3424. begin
  3425. Sysutils.CurrencyFormat:=AValue;
  3426. end;
  3427. procedure TFormatSettings.SetCurrencyString(AValue: String);
  3428. begin
  3429. Sysutils.CurrencyString:=AValue;
  3430. end;
  3431. procedure TFormatSettings.SetDateSeparator(const Value: char);
  3432. begin
  3433. SysUtils.DateSeparator := Value;
  3434. end;
  3435. procedure TFormatSettings.SetDecimalSeparator(const Value: string);
  3436. begin
  3437. SysUtils.DecimalSeparator := Value;
  3438. end;
  3439. procedure TFormatSettings.SetLongDateFormat(const Value: string);
  3440. begin
  3441. SysUtils.LongDateFormat := Value;
  3442. end;
  3443. procedure TFormatSettings.SetLongDayNames(AValue: TDayNames);
  3444. begin
  3445. SysUtils.LongDayNames:=AValue;
  3446. end;
  3447. procedure TFormatSettings.SetLongMonthNames(AValue: TMonthNames);
  3448. begin
  3449. SysUtils.LongMonthNames:=AValue;
  3450. end;
  3451. procedure TFormatSettings.SetLongTimeFormat(const Value: string);
  3452. begin
  3453. SysUtils.LongTimeFormat := Value;
  3454. end;
  3455. procedure TFormatSettings.SetNegCurrFormat(AValue: Byte);
  3456. begin
  3457. Sysutils.NegCurrFormat:=AValue;
  3458. end;
  3459. procedure TFormatSettings.SetShortDateFormat(const Value: string);
  3460. begin
  3461. SysUtils.ShortDateFormat := Value;
  3462. end;
  3463. procedure TFormatSettings.SetShortDayNames(AValue: TDayNames);
  3464. begin
  3465. SysUtils.ShortDayNames:=AValue;
  3466. end;
  3467. procedure TFormatSettings.SetShortMonthNames(AValue: TMonthNames);
  3468. begin
  3469. SysUtils.ShortMonthNames:=AValue;
  3470. end;
  3471. procedure TFormatSettings.SetShortTimeFormat(const Value: string);
  3472. begin
  3473. SysUtils.ShortTimeFormat := Value;
  3474. end;
  3475. procedure TFormatSettings.SetCurrencyDecimals(AValue: Byte);
  3476. begin
  3477. Sysutils.CurrencyDecimals:=aValue;
  3478. end;
  3479. procedure TFormatSettings.SetThousandSeparator(const Value: string);
  3480. begin
  3481. SysUtils.ThousandSeparator := Value;
  3482. end;
  3483. procedure TFormatSettings.SetTimeAMString(const Value: string);
  3484. begin
  3485. SysUtils.TimeAMString := Value;
  3486. end;
  3487. procedure TFormatSettings.SetTimePMString(const Value: string);
  3488. begin
  3489. SysUtils.TimePMString := Value;
  3490. end;
  3491. procedure TFormatSettings.SetTimeSeparator(const Value: char);
  3492. begin
  3493. SysUtils.TimeSeparator := Value;
  3494. end;
  3495. initialization
  3496. FormatSettings := TFormatSettings.Create;
  3497. end.