sysutils.pas 109 KB

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