sysutils.pas 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086
  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[i]=TS);
  1428. if not Result then
  1429. break;
  1430. end;
  1431. if (Result) and (AValue[1]='-') 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. D : Double;
  1439. Begin
  1440. D:=Value;
  1441. // Writeln('Value ',D);
  1442. If Digits = -1 Then
  1443. Digits := CurrencyDecimals
  1444. Else If Digits > 18 Then
  1445. Digits := 18;
  1446. Str(D:0:Digits, Result);
  1447. // Writeln('1. Result ',Result,' currencystring : ',CurrencyString);
  1448. Negative:=Result[1] = '-';
  1449. if Negative then
  1450. System.Delete(Result, 1, 1);
  1451. P := Pos('.', Result);
  1452. // Writeln('2. Result ',Result,' currencystring : ',CurrencyString);
  1453. If TS<>'' Then
  1454. begin
  1455. If P <> 0 Then
  1456. Result:=ReplaceDecimalSep(Result,DS)
  1457. else
  1458. P := Length(Result)+1;
  1459. Dec(P, 3);
  1460. While (P > 1) Do
  1461. Begin
  1462. Insert(TS, Result, P);
  1463. Dec(P, 3);
  1464. End;
  1465. end;
  1466. // Writeln('3. Result ',Result,' currencystring : ',CurrencyString);
  1467. if Negative then
  1468. RemoveLeadingNegativeSign(Result,DS);
  1469. // Writeln('4. Result ',Result,' currencystring : ',CurrencyString);
  1470. // Writeln('CurrencyFormat: ',CurrencyFormat,'NegcurrencyFormat: ',NegCurrFormat);
  1471. If Not Negative Then
  1472. Case CurrencyFormat Of
  1473. 0: Result := CurrencyString + Result;
  1474. 1: Result := Result + CurrencyString;
  1475. 2: Result := CurrencyString + ' ' + Result;
  1476. 3: Result := Result + ' ' + CurrencyString;
  1477. end
  1478. else
  1479. Case NegCurrFormat Of
  1480. 0: Result := '(' + CurrencyString + Result + ')';
  1481. 1: Result := '-' + CurrencyString + Result;
  1482. 2: Result := CurrencyString + '-' + Result;
  1483. 3: Result := CurrencyString + Result + '-';
  1484. 4: Result := '(' + Result + CurrencyString + ')';
  1485. 5: Result := '-' + Result + CurrencyString;
  1486. 6: Result := Result + '-' + CurrencyString;
  1487. 7: Result := Result + CurrencyString + '-';
  1488. 8: Result := '-' + Result + ' ' + CurrencyString;
  1489. 9: Result := '-' + CurrencyString + ' ' + Result;
  1490. 10: Result := Result + ' ' + CurrencyString + '-';
  1491. 11: Result := CurrencyString + ' ' + Result + '-';
  1492. 12: Result := CurrencyString + ' ' + '-' + Result;
  1493. 13: Result := Result + '-' + ' ' + CurrencyString;
  1494. 14: Result := '(' + CurrencyString + ' ' + Result + ')';
  1495. 15: Result := '(' + Result + ' ' + CurrencyString + ')';
  1496. end;
  1497. end;
  1498. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  1499. Var
  1500. DS: string;
  1501. Begin
  1502. DS:=DecimalSeparator;
  1503. Case format Of
  1504. ffGeneral:
  1505. Result:=FormatGeneralFloat(Value,Precision,DS);
  1506. ffExponent:
  1507. Result:=FormatExponentFloat(Value,Precision,Digits,DS);
  1508. ffFixed:
  1509. Result:=FormatFixedFloat(Value,Digits,DS);
  1510. ffNumber:
  1511. Result:=FormatNumberFloat(Value,Digits,DS,ThousandSeparator);
  1512. ffCurrency:
  1513. Result:=FormatNumberCurrency(Value,Digits,DS,ThousandSeparator);
  1514. end;
  1515. if (Format<>ffCurrency) and (length(Result)>1) and (Result[1]='-') then
  1516. RemoveLeadingNegativeSign(Result,DS);
  1517. end;
  1518. function Format (const Fmt: String; const Args: array of jsvalue): String;
  1519. Var ChPos,OldPos,ArgPos,DoArg,Len : SizeInt;
  1520. Hs,ToAdd : String;
  1521. Index : SizeInt;
  1522. Width,Prec : Longint;
  1523. Left : Boolean;
  1524. Fchar : char;
  1525. vq : nativeint;
  1526. {
  1527. ReadFormat reads the format string. It returns the type character in
  1528. uppercase, and sets index, Width, Prec to their correct values,
  1529. or -1 if not set. It sets Left to true if left alignment was requested.
  1530. In case of an error, DoFormatError is called.
  1531. }
  1532. Function ReadFormat : Char;
  1533. Var Value : NativeInt;
  1534. Procedure ReadInteger;
  1535. var
  1536. Code: integer;
  1537. ArgN: SizeInt;
  1538. begin
  1539. If Value<>-1 then exit; // Was already read.
  1540. OldPos:=ChPos;
  1541. While (ChPos<=Len) and
  1542. (Fmt[ChPos]<='9') and (Fmt[ChPos]>='0') do inc(ChPos);
  1543. If ChPos>len then
  1544. DoFormatError(feInvalidFormat,Fmt);
  1545. If Fmt[ChPos]='*' then
  1546. begin
  1547. if Index=-1 then
  1548. ArgN:=Argpos
  1549. else
  1550. begin
  1551. ArgN:=Index;
  1552. Inc(Index);
  1553. end;
  1554. If (ChPos>OldPos) or (ArgN>High(Args)) then
  1555. DoFormatError(feInvalidFormat,Fmt);
  1556. ArgPos:=ArgN+1;
  1557. if IsNumber(Args[ArgN]) and IsInteger(Args[ArgN]) then
  1558. Value:=Integer(Args[ArgN])
  1559. else
  1560. DoFormatError(feInvalidFormat,Fmt);
  1561. Inc(ChPos);
  1562. end
  1563. else
  1564. begin
  1565. If (OldPos<ChPos) Then
  1566. begin
  1567. Val (Copy(Fmt,OldPos,ChPos-OldPos),value,code);
  1568. // This should never happen !!
  1569. If Code>0 then DoFormatError (feInvalidFormat,Fmt);
  1570. end
  1571. else
  1572. Value:=-1;
  1573. end;
  1574. end;
  1575. Procedure ReadIndex;
  1576. begin
  1577. If Fmt[ChPos]<>':' then
  1578. ReadInteger
  1579. else
  1580. value:=0; // Delphi undocumented behaviour, assume 0, #11099
  1581. If Fmt[ChPos]=':' then
  1582. begin
  1583. If Value=-1 then DoFormatError(feMissingArgument,Fmt);
  1584. Index:=Value;
  1585. Value:=-1;
  1586. Inc(ChPos);
  1587. end;
  1588. end;
  1589. Procedure ReadLeft;
  1590. begin
  1591. If Fmt[ChPos]='-' then
  1592. begin
  1593. left:=True;
  1594. Inc(ChPos);
  1595. end
  1596. else
  1597. Left:=False;
  1598. end;
  1599. Procedure ReadWidth;
  1600. begin
  1601. ReadInteger;
  1602. If Value<>-1 then
  1603. begin
  1604. Width:=Value;
  1605. Value:=-1;
  1606. end;
  1607. end;
  1608. Procedure ReadPrec;
  1609. begin
  1610. If Fmt[ChPos]='.' then
  1611. begin
  1612. inc(ChPos);
  1613. ReadInteger;
  1614. If Value=-1 then
  1615. Value:=0;
  1616. prec:=Value;
  1617. end;
  1618. end;
  1619. begin
  1620. Index:=-1;
  1621. Width:=-1;
  1622. Prec:=-1;
  1623. Value:=-1;
  1624. inc(ChPos);
  1625. If Fmt[ChPos]='%' then
  1626. begin
  1627. Result:='%';
  1628. exit; // VP fix
  1629. end;
  1630. ReadIndex;
  1631. ReadLeft;
  1632. ReadWidth;
  1633. ReadPrec;
  1634. Result:=Upcase(Fmt[ChPos]);
  1635. end;
  1636. function Checkarg (AT : TJSValueType; err:boolean):boolean;
  1637. {
  1638. Check if argument INDEX is of correct type (AT)
  1639. If Index=-1, ArgPos is used, and argpos is augmented with 1
  1640. DoArg is set to the argument that must be used.
  1641. }
  1642. begin
  1643. result:=false;
  1644. if Index=-1 then
  1645. DoArg:=Argpos
  1646. else
  1647. DoArg:=Index;
  1648. ArgPos:=DoArg+1;
  1649. If (Doarg>High(Args)) or (GetValueTYpe(Args[Doarg])<>AT) then
  1650. begin
  1651. if err then
  1652. DoFormatError(feInvalidArgindex,Fmt);
  1653. dec(ArgPos);
  1654. exit;
  1655. end;
  1656. result:=true;
  1657. end;
  1658. begin
  1659. Result:='';
  1660. Len:=Length(Fmt);
  1661. ChPos:=1;
  1662. OldPos:=1;
  1663. ArgPos:=0;
  1664. While ChPos<=len do
  1665. begin
  1666. While (ChPos<=Len) and (Fmt[ChPos]<>'%') do
  1667. inc(ChPos);
  1668. If ChPos>OldPos Then
  1669. Result:=Result+Copy(Fmt,OldPos,ChPos-Oldpos);
  1670. If ChPos<Len then
  1671. begin
  1672. FChar:=ReadFormat;
  1673. {$ifdef fmtdebug}
  1674. DumpFormat(FCHar);
  1675. {$endif}
  1676. Case FChar of
  1677. 'D' : begin
  1678. Checkarg(jvtinteger,true);
  1679. toAdd:=IntToStr(NativeInt(Args[DoArg]));
  1680. Width:=Abs(width);
  1681. Index:=Prec-Length(ToAdd);
  1682. If ToAdd[1]<>'-' then
  1683. ToAdd:=StringOfChar('0',Index)+ToAdd
  1684. else
  1685. // + 1 to accomodate for - sign in length !!
  1686. Insert(StringOfChar('0',Index+1),toadd,2);
  1687. end;
  1688. 'U' : begin
  1689. Checkarg(jvtinteger,True);
  1690. if NativeInt(Args[Doarg])<0 then
  1691. DoFormatError(feInvalidArgindex,Fmt);
  1692. Toadd:=IntToStr(NativeInt(Args[Doarg]));
  1693. Width:=Abs(width);
  1694. Index:=Prec-Length(ToAdd);
  1695. ToAdd:=StringOfChar('0',Index)+ToAdd
  1696. end;
  1697. 'E' : begin
  1698. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1699. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1700. end;
  1701. 'F' : begin
  1702. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1703. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1704. end;
  1705. 'G' : begin
  1706. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1707. ToAdd:=FloatToStrF(Double(Args[doarg]),ffGeneral,Prec,3);
  1708. end;
  1709. 'N' : begin
  1710. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1711. ToAdd:=FloatToStrF(Double(Args[doarg]),ffNumber,9999,Prec);
  1712. end;
  1713. 'M' : begin
  1714. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1715. ToAdd:=FloatToStrF(Double(Args[doarg]),ffCurrency,9999,Prec);
  1716. end;
  1717. 'S' : begin
  1718. CheckArg(jvtString,true);
  1719. hs:=String(Args[doarg]);
  1720. Index:=Length(hs);
  1721. If (Prec<>-1) and (Index>Prec) then
  1722. Index:=Prec;
  1723. ToAdd:=Copy(hs,1,Index);
  1724. end;
  1725. 'P' : Begin
  1726. CheckArg(jvtInteger,true);
  1727. ToAdd:=IntToHex(NativeInt(Args[DoArg]),31);
  1728. end;
  1729. 'X' : begin
  1730. Checkarg(jvtinteger,true);
  1731. vq:=nativeInt(Args[Doarg]);
  1732. index:=31; // May need to adjust to NativeInt
  1733. If Prec>index then
  1734. ToAdd:=IntToHex(vq,index)
  1735. else
  1736. begin
  1737. // determine minimum needed number of hex digits.
  1738. Index:=1;
  1739. While (NativeInt(1) shl (Index*4)<=vq) and (index<16) do
  1740. inc(Index);
  1741. If Index>Prec then
  1742. Prec:=Index;
  1743. ToAdd:=IntToHex(vq,Prec);
  1744. end;
  1745. end;
  1746. '%': ToAdd:='%';
  1747. end;
  1748. If Width<>-1 then
  1749. If Length(ToAdd)<Width then
  1750. If not Left then
  1751. ToAdd:=StringOfChar(' ',Width-Length(ToAdd))+ToAdd
  1752. else
  1753. ToAdd:=ToAdd+StringOfChar(' ',Width-Length(ToAdd));
  1754. Result:=Result+ToAdd;
  1755. end;
  1756. inc(ChPos);
  1757. Oldpos:=ChPos;
  1758. end;
  1759. end;
  1760. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler;
  1761. asm
  1762. return s1.localeCompare(s2,locales) == 0;
  1763. end;
  1764. function NormalizeStr(const S: String; const Norm: String): String; assembler;
  1765. asm
  1766. return S.normalize(Norm);
  1767. end;
  1768. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  1769. const
  1770. Alpha = ['A'..'Z', 'a'..'z', '_'];
  1771. AlphaNum = Alpha + ['0'..'9'];
  1772. Dot = '.';
  1773. var
  1774. First: Boolean;
  1775. I, Len: Integer;
  1776. begin
  1777. Len := Length(Ident);
  1778. if Len < 1 then
  1779. Exit(False);
  1780. First := True;
  1781. Result:=false;
  1782. I:=1;
  1783. While I<=len do
  1784. begin
  1785. if First then
  1786. begin
  1787. if not (Ident[I] in Alpha) then exit;
  1788. First := False;
  1789. end
  1790. else if AllowDots and (Ident[I] = Dot) then
  1791. begin
  1792. if StrictDots then
  1793. begin
  1794. if I >= Len then exit;
  1795. First := True;
  1796. end;
  1797. end
  1798. else
  1799. if not (Ident[I] in AlphaNum) then exit;
  1800. I:=I+1;
  1801. end;
  1802. Result:=true;
  1803. end;
  1804. procedure FreeAndNil(var Obj);
  1805. var
  1806. o: TObject;
  1807. begin
  1808. o:=TObject(Obj);
  1809. if o=nil then exit;
  1810. TObject(Obj):=nil;
  1811. o.Destroy;
  1812. end;
  1813. { EVariantError }
  1814. constructor EVariantError.CreateCode(Code: Longint);
  1815. begin
  1816. ErrCode:=Code;
  1817. end;
  1818. { Exception }
  1819. constructor Exception.Create(const Msg: String);
  1820. begin
  1821. fMessage:=Msg;
  1822. {$ifdef nodejs}
  1823. FNodeJSError:=TJSError.new;
  1824. {$endif}
  1825. end;
  1826. constructor Exception.CreateFmt(const Msg: string; const Args: array of jsvalue
  1827. );
  1828. begin
  1829. //writeln('Exception.CreateFmt START ',ClassName,' "',Msg,'" Args=',Args);
  1830. Create(Format(Msg,Args));
  1831. //writeln('Exception.CreateFmt END ',ClassName,' "',Msg,'" fMessage=',fMessage);
  1832. end;
  1833. constructor Exception.CreateHelp(const Msg: String; AHelpContext: Integer);
  1834. begin
  1835. Create(Msg);
  1836. fHelpContext:=AHelpContext;
  1837. end;
  1838. constructor Exception.CreateFmtHelp(const Msg: string;
  1839. const Args: array of jsvalue; AHelpContext: Integer);
  1840. begin
  1841. Create(Format(Msg,Args));
  1842. fHelpContext:=AHelpContext;
  1843. end;
  1844. function Exception.ToString: String;
  1845. begin
  1846. Result:=ClassName+': '+Message;
  1847. end;
  1848. Const
  1849. RESpecials = '([\[\]\(\)\\\.\*])';
  1850. Function StringReplace(aOriginal, aSearch, aReplace : string; Flags : TStringReplaceFlags) : String;
  1851. Var
  1852. REFlags : String;
  1853. REString : String;
  1854. begin
  1855. REFlags:='';
  1856. if rfReplaceAll in flags then
  1857. ReFlags:='g';
  1858. if rfIgnoreCase in flags then
  1859. ReFlags:=ReFlags+'i';
  1860. REString:=TJSString(aSearch).replace(TJSRegexp.new(RESpecials,'g'),'\$1');
  1861. Result:=TJSString(aOriginal).replace(TJSRegexp.new(REString,REFlags),aReplace);
  1862. end;
  1863. Function QuoteString(aOriginal : String; AQuote : Char) : String;
  1864. begin
  1865. Result:=AQuote+StringReplace(aOriginal,aQuote,aQuote+aQuote,[rfReplaceAll])+AQuote;
  1866. end;
  1867. function QuotedStr(const s: string; QuoteChar : Char = ''''): string;
  1868. begin
  1869. Result:=QuoteString(S,QuoteChar);
  1870. end;
  1871. function DeQuoteString(aQuoted: String; AQuote: Char): String;
  1872. var
  1873. i: Integer;
  1874. begin
  1875. Result:=aQuoted;
  1876. if TJSString(Result).substr(0,1)<>AQuote then exit;
  1877. Result:=TJSString(Result).slice(1);
  1878. i:=1;
  1879. while i<=length(Result) do
  1880. begin
  1881. if Result[i]=AQuote then
  1882. begin
  1883. if (i=length(Result)) or (Result[i+1]<>AQuote) then
  1884. begin
  1885. Result:=TJSString(Result).slice(0,i-1);
  1886. exit;
  1887. end
  1888. else
  1889. Result:=TJSString(Result).slice(0,i-1)+TJSString(Result).slice(i);
  1890. end
  1891. else
  1892. inc(i);
  1893. end;
  1894. end;
  1895. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  1896. begin
  1897. Result:=False;
  1898. if (Index>0) and (Index<=Length(S)) then
  1899. Result:=Pos(S[Index],Delimiters)<>0; // Note we don't do MBCS yet
  1900. end;
  1901. function AdjustLineBreaks(const S: string): string;
  1902. begin
  1903. Result:=AdjustLineBreaks(S,DefaultTextLineBreakStyle);
  1904. end;
  1905. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  1906. var
  1907. I,L: Longint;
  1908. Res : String;
  1909. Procedure Add(C : Char);
  1910. begin
  1911. Res:=Res+C;
  1912. end;
  1913. begin
  1914. I:=0;
  1915. L:=Length(S);
  1916. Result:='';
  1917. While (I<=L) do
  1918. case S[I] of
  1919. #10: begin
  1920. if Style in [tlbsCRLF,tlbsCR] then
  1921. Add(#13);
  1922. if Style=tlbsCRLF then
  1923. Add(#10);
  1924. Inc(I);
  1925. end;
  1926. #13: begin
  1927. if Style=tlbsCRLF then
  1928. Add(#13);
  1929. Add(#10);
  1930. Inc(I);
  1931. if S[I]=#10 then
  1932. Inc(I);
  1933. end;
  1934. else
  1935. Add(S[i]);
  1936. Inc(I);
  1937. end;
  1938. Result:=Res;
  1939. end;
  1940. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  1941. const
  1942. Quotes = ['''', '"'];
  1943. Var
  1944. L : String;
  1945. C,LQ,BC : Char;
  1946. P,BLen,Len : Integer;
  1947. HB,IBC : Boolean;
  1948. begin
  1949. Result:='';
  1950. L:=Line;
  1951. Blen:=Length(BreakStr);
  1952. If (BLen>0) then
  1953. BC:=BreakStr[1]
  1954. else
  1955. BC:=#0;
  1956. Len:=Length(L);
  1957. While (Len>0) do
  1958. begin
  1959. P:=1;
  1960. LQ:=#0;
  1961. HB:=False;
  1962. IBC:=False;
  1963. While ((P<=Len) and ((P<=MaxCol) or not IBC)) and ((LQ<>#0) or Not HB) do
  1964. begin
  1965. C:=L[P];
  1966. If (C=LQ) then
  1967. LQ:=#0
  1968. else If (C in Quotes) then
  1969. LQ:=C;
  1970. If (LQ<>#0) then
  1971. Inc(P)
  1972. else
  1973. begin
  1974. HB:=((C=BC) and (BreakStr=Copy(L,P,BLen)));
  1975. If HB then
  1976. Inc(P,Blen)
  1977. else
  1978. begin
  1979. If (P>=MaxCol) then
  1980. IBC:=CharInSet(C,BreakChars);
  1981. Inc(P);
  1982. end;
  1983. end;
  1984. // Writeln('"',C,'" : IBC : ',IBC,' HB : ',HB,' LQ : ',LQ,' P>MaxCol : ',P>MaxCol);
  1985. end;
  1986. Result:=Result+Copy(L,1,P-1);
  1987. Delete(L,1,P-1);
  1988. Len:=Length(L);
  1989. If (Len>0) and Not HB then
  1990. Result:=Result+BreakStr;
  1991. end;
  1992. end;
  1993. function WrapText(const Line: string; MaxCol: Integer): string;
  1994. begin
  1995. Result:=WrapText(Line,sLineBreak, [' ', '-', #9], MaxCol);
  1996. end;
  1997. function GetEnvironmentVariable(const EnvVar: String): String;
  1998. begin
  1999. if Assigned(OnGetEnvironmentVariable) then
  2000. Result:=OnGetEnvironmentVariable(EnvVar)
  2001. else
  2002. Result:='';
  2003. end;
  2004. function GetEnvironmentVariableCount: Integer;
  2005. begin
  2006. if Assigned(OnGetEnvironmentVariableCount) then
  2007. Result:=OnGetEnvironmentVariableCount()
  2008. else
  2009. Result:=0;
  2010. end;
  2011. function GetEnvironmentString(Index: Integer): String;
  2012. begin
  2013. if Assigned(OnGetEnvironmentString) then
  2014. Result:=OnGetEnvironmentString(Index)
  2015. else
  2016. Result:='';
  2017. end;
  2018. { Date/Time routines}
  2019. Function DoEncodeDate(Year, Month, Day: Word): longint;
  2020. Var
  2021. D : TDateTime;
  2022. begin
  2023. If TryEncodeDate(Year,Month,Day,D) then
  2024. Result:=Trunc(D)
  2025. else
  2026. Result:=0;
  2027. end;
  2028. function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime;
  2029. begin
  2030. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2031. Result:=0;
  2032. end;
  2033. Function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  2034. Var
  2035. Y,M,D,h,n,s,z : Word;
  2036. begin
  2037. DecodeDate(Trunc(aDateTime),Y,M,D);
  2038. DecodeTime(Frac(aDateTime),H,N,S,Z);
  2039. Result:=TJSDate.New(Y,M,D,h,n,s,z);
  2040. end;
  2041. Function JSDatetoDateTime(ADate: TJSDate) : TDateTime;
  2042. begin
  2043. Result:=EncodeDate(ADate.FullYear,ADate.Month+1,ADate.Date) +
  2044. EncodeTime(ADate.Hours,ADate.Minutes,ADate.Seconds,ADate.Milliseconds);
  2045. end;
  2046. { ComposeDateTime converts a Date and a Time into one TDateTime }
  2047. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  2048. begin
  2049. if Date < 0 then
  2050. Result := trunc(Date) - Abs(frac(Time))
  2051. else
  2052. Result := trunc(Date) + Abs(frac(Time));
  2053. end;
  2054. Function TryEncodeDate(Year,Month,Day : Word; Out Date : TDateTime) : Boolean;
  2055. var
  2056. c, ya: LongWord;
  2057. begin
  2058. Result:=(Year>0) and (Year<10000) and
  2059. (Month >= 1) and (Month<=12) and
  2060. (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]);
  2061. If Result then
  2062. begin
  2063. if month > 2 then
  2064. Dec(Month,3)
  2065. else
  2066. begin
  2067. Inc(Month,9);
  2068. Dec(Year);
  2069. end;
  2070. c:= Year DIV 100;
  2071. ya:= Year - 100*c;
  2072. Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*LongWord(Month)+2) DIV 5 + LongWord(Day);
  2073. // Note that this line can't be part of the line above, since TDateTime is
  2074. // signed and c and ya are not
  2075. Date := Date - 693900;
  2076. end
  2077. end;
  2078. function TryEncodeTime(Hour, Min, Sec, MSec:word; Out Time : TDateTime) : boolean;
  2079. begin
  2080. Result:=(Hour<24) and (Min<60) and (Sec<60) and (MSec<1000);
  2081. If Result then
  2082. Time:=TDateTime(LongWord(Hour)*3600000+LongWord(Min)*60000+LongWord(Sec)*1000+MSec)/MSecsPerDay;
  2083. end;
  2084. { EncodeDate packs three variables Year, Month and Day into a
  2085. TDateTime value the result is the number of days since 12/30/1899 }
  2086. function EncodeDate(Year, Month, Day: word): TDateTime;
  2087. begin
  2088. If Not TryEncodeDate(Year,Month,Day,Result) then
  2089. Raise EConvertError.CreateFmt('%s-%s-%s is not a valid date specification',
  2090. [IntToStr(Year),IntToStr(Month),IntToStr(Day)]);
  2091. end;
  2092. { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into
  2093. a TDateTime value }
  2094. function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime;
  2095. begin
  2096. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2097. Raise EConvertError.CreateFmt('%s:%s:%s.%s is not a valid time specification',
  2098. [IntToStr(Hour),IntToStr(Minute),IntToStr(Second),IntToStr(MilliSecond)]);
  2099. end;
  2100. { DecodeDate unpacks the value Date into three values:
  2101. Year, Month and Day }
  2102. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  2103. var
  2104. ly,ld,lm,j : LongWord;
  2105. begin
  2106. if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0
  2107. begin
  2108. Year := 0;
  2109. Month := 0;
  2110. Day := 0;
  2111. end
  2112. else
  2113. begin
  2114. if Date>0 then
  2115. Date:=(Date+(1/(msecsperday*2)))
  2116. else
  2117. Date:=Date-(1/(msecsperday*2));
  2118. if Date>MaxDateTime then
  2119. Date:=MaxDateTime;
  2120. // Raise EConvertError.CreateFmt('%f is not a valid TDatetime encoding, maximum value is %f.',[Date,MaxDateTime]);
  2121. j := ((Trunc(Date) + 693900) SHL 2)-1;
  2122. ly:= j DIV 146097;
  2123. j:= j - 146097 * LongWord(ly);
  2124. ld := j SHR 2;
  2125. j:=(ld SHL 2 + 3) DIV 1461;
  2126. ld:= ((ld SHL 2) + 7 - 1461*j) SHR 2;
  2127. lm:=(5 * ld-3) DIV 153;
  2128. ld:= (5 * ld +2 - 153*lm) DIV 5;
  2129. ly:= 100 * LongWord(ly) + j;
  2130. if lm < 10 then
  2131. inc(lm,3)
  2132. else
  2133. begin
  2134. dec(lm,9);
  2135. inc(ly);
  2136. end;
  2137. year:=ly;
  2138. month:=lm;
  2139. day:=ld;
  2140. end;
  2141. end;
  2142. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  2143. begin
  2144. DecodeDate(DateTime,Year,Month,Day);
  2145. DOW:=DayOfWeek(DateTime);
  2146. Result:=IsLeapYear(Year);
  2147. end;
  2148. { DateTimeToTimeStamp converts DateTime to a TTimeStamp }
  2149. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  2150. Var
  2151. D : Double;
  2152. begin
  2153. D:=DateTime * Double(MSecsPerDay);
  2154. if D<0 then
  2155. D:=D-0.5
  2156. else
  2157. D:=D+0.5;
  2158. result.Time := Trunc(Abs(Trunc(D)) Mod MSecsPerDay);
  2159. result.Date := DateDelta + (Trunc(D) div MSecsPerDay);
  2160. end;
  2161. { TimeStampToDateTime converts TimeStamp to a TDateTime value }
  2162. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  2163. begin
  2164. Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time/MSecsPerDay)
  2165. end;
  2166. { MSecsToTimeStamp }
  2167. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  2168. begin
  2169. result.Date := Trunc(msecs/msecsperday);
  2170. msecs:= msecs-NativeInt(result.date)*msecsperday;
  2171. result.Time := Round(MSecs);
  2172. end;
  2173. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  2174. begin
  2175. result := TimeStamp.Time + (timestamp.date*msecsperday);
  2176. end ;
  2177. { DecodeTime unpacks Time into four values:
  2178. Hour, Minute, Second and MilliSecond }
  2179. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  2180. Var
  2181. l : LongWord;
  2182. begin
  2183. l := DateTimeToTimeStamp(Time).Time;
  2184. Hour := l div 3600000;
  2185. l := l mod 3600000;
  2186. Minute := l div 60000;
  2187. l := l mod 60000;
  2188. Second := l div 1000;
  2189. l := l mod 1000;
  2190. MilliSecond := l;
  2191. end;
  2192. { DateTimeToSystemTime converts DateTime value to SystemTime }
  2193. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  2194. begin
  2195. DecodeDateFully(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.DayOfWeek);
  2196. DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond);
  2197. Dec(SystemTime.DayOfWeek);
  2198. end ;
  2199. { SystemTimeToDateTime converts SystemTime to a TDateTime value }
  2200. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  2201. begin
  2202. result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day),
  2203. DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond));
  2204. end ;
  2205. function DayOfWeek(DateTime: TDateTime): integer;
  2206. begin
  2207. Result := 1 + ((Trunc(DateTime) - 1) mod 7);
  2208. If (Result<=0) then
  2209. Inc(Result,7);
  2210. end;
  2211. function Now: TDateTime;
  2212. begin
  2213. Result:=JSDateToDateTime(TJSDate.New());
  2214. end;
  2215. function Date: TDateTime;
  2216. begin
  2217. Result:=Trunc(Now);
  2218. end;
  2219. function Time: TDateTime;
  2220. begin
  2221. Result:=Now-Date;
  2222. end ;
  2223. { IncMonth increments DateTime with NumberOfMonths months,
  2224. NumberOfMonths can be less than zero }
  2225. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  2226. var
  2227. Year, Month, Day : word;
  2228. begin
  2229. DecodeDate(DateTime, Year, Month, Day);
  2230. IncAMonth(Year, Month, Day, NumberOfMonths);
  2231. result := ComposeDateTime(DoEncodeDate(Year, Month, Day), DateTime);
  2232. end ;
  2233. { IncAMonth is the same as IncMonth, but operates on decoded date }
  2234. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  2235. var
  2236. TempMonth, S: Integer;
  2237. begin
  2238. If NumberOfMonths>=0 then
  2239. s:=1
  2240. else
  2241. s:=-1;
  2242. inc(Year,(NumberOfMonths div 12));
  2243. TempMonth:=Month+(NumberOfMonths mod 12)-1;
  2244. if (TempMonth>11) or
  2245. (TempMonth<0) then
  2246. begin
  2247. Dec(TempMonth, S*12);
  2248. Inc(Year, S);
  2249. end;
  2250. Month:=TempMonth+1; { Months from 1 to 12 }
  2251. If (Day>MonthDays[IsLeapYear(Year)][Month]) then
  2252. Day:=MonthDays[IsLeapYear(Year)][Month];
  2253. end;
  2254. { IsLeapYear returns true if Year is a leap year }
  2255. function IsLeapYear(Year: Word): boolean;
  2256. begin
  2257. Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
  2258. end;
  2259. { DateToStr returns a string representation of Date using ShortDateFormat }
  2260. function DateToStr(Date: TDateTime): string;
  2261. begin
  2262. Result:=FormatDateTime('ddddd', Date);
  2263. end ;
  2264. { TimeToStr returns a string representation of Time using LongTimeFormat }
  2265. function TimeToStr(Time: TDateTime): string;
  2266. begin
  2267. Result:=FormatDateTime('tt',Time);
  2268. end ;
  2269. { DateTimeToStr returns a string representation of DateTime using LongDateTimeFormat }
  2270. Var
  2271. DateTimeToStrFormat : Array[Boolean] of string = ('c','f');
  2272. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  2273. begin
  2274. Result:=FormatDateTime(DateTimeToStrFormat[ForceTimeIfZero], DateTime)
  2275. end ;
  2276. { StrToDate converts the string S to a TDateTime value
  2277. if S does not represent a valid date value
  2278. an EConvertError will be raised }
  2279. function IntStrToDate(Out ErrorMsg : String; const S: String; const useformat : string; separator : char): TDateTime;
  2280. Const
  2281. WhiteSpace = ' '#8#9#10#12#13;
  2282. Digits = '0123456789';
  2283. procedure FixErrorMsg(const errmarg : String);
  2284. begin
  2285. ErrorMsg:=Format(SInvalidDateFormat,[errmarg]);
  2286. end;
  2287. var
  2288. df:string;
  2289. d,m,y,ly,ld,lm:word;
  2290. n,i,len:longint;
  2291. c: integer;
  2292. dp,mp,yp,which : Byte;
  2293. s1:string;
  2294. values: array of integer;
  2295. YearMoreThenTwoDigits : boolean;
  2296. begin
  2297. SetLength(values,4);
  2298. Result:=0;
  2299. Len:=Length(S);
  2300. ErrorMsg:='';
  2301. While (Len>0) and (Pos(S[Len],WhiteSpace)>0) do
  2302. Dec(len);
  2303. if (Len=0) then
  2304. begin
  2305. FixErrorMsg(S);
  2306. exit;
  2307. end;
  2308. YearMoreThenTwoDigits := False;
  2309. if separator = #0 then
  2310. if (DateSeparator<>#0) then
  2311. separator := DateSeparator
  2312. else
  2313. separator:='-';
  2314. // Writeln('Separator: ',Separator);
  2315. df := UpperCase(useFormat);
  2316. { Determine order of D,M,Y }
  2317. yp:=0;
  2318. mp:=0;
  2319. dp:=0;
  2320. Which:=0;
  2321. i:=0;
  2322. while (i<Length(df)) and (Which<3) do
  2323. begin
  2324. inc(i);
  2325. Case df[i] of
  2326. 'Y' :
  2327. if yp=0 then
  2328. begin
  2329. Inc(Which);
  2330. yp:=which;
  2331. end;
  2332. 'M' :
  2333. if mp=0 then
  2334. begin
  2335. Inc(Which);
  2336. mp:=which;
  2337. end;
  2338. 'D' :
  2339. if dp=0 then
  2340. begin
  2341. Inc(Which);
  2342. dp:=which;
  2343. end;
  2344. end;
  2345. end;
  2346. // Writeln('YP: ',Yp,', MP: ',Mp,', DP: ',DP);
  2347. for i := 1 to 3 do
  2348. values[i] := 0;
  2349. s1 := '';
  2350. n := 0;
  2351. for i := 1 to len do
  2352. begin
  2353. if Pos(s[i],Digits)>0 then
  2354. s1 := s1 + s[i];
  2355. { space can be part of the shortdateformat, and is defaultly in slovak
  2356. windows, therefor it shouldn't be taken as separator (unless so specified)
  2357. and ignored }
  2358. if (Separator <> ' ') and (s[i] = ' ') then
  2359. Continue;
  2360. if (s[i] = separator) or ((i = len) and (Pos(s[i],Digits)>0)) then
  2361. begin
  2362. inc(n);
  2363. if n>3 then
  2364. begin
  2365. // Writeln('More than 3 separators');
  2366. FixErrorMsg(S);
  2367. exit;
  2368. end;
  2369. // Check if the year has more then two digits (if n=yp, then we are evaluating the year.)
  2370. if (n=yp) and (length(s1)>2) then YearMoreThenTwoDigits := True;
  2371. val(s1, values[n], c);
  2372. if c<>0 then
  2373. begin
  2374. // Writeln('S1 not a number ',S1);
  2375. FixErrorMsg(s);
  2376. Exit;
  2377. end;
  2378. s1 := '';
  2379. end
  2380. else if (Pos(s[i],Digits)=0) then
  2381. begin
  2382. // Writeln('Not a number at pos ',I,' ',S[i]);
  2383. FixErrorMsg(s);
  2384. Exit;
  2385. end;
  2386. end ;
  2387. // Writeln('Which : ',Which,' N : ',N);
  2388. if (Which<3) and (N>Which) then
  2389. begin
  2390. FixErrorMsg(s);
  2391. Exit;
  2392. end;
  2393. // Fill in values.
  2394. DecodeDate(Date,Ly,LM,LD);
  2395. If N=3 then
  2396. begin
  2397. y:=values[yp];
  2398. m:=values[mp];
  2399. d:=values[dp];
  2400. end
  2401. Else
  2402. begin
  2403. Y:=ly;
  2404. If n<2 then
  2405. begin
  2406. d:=values[1];
  2407. m := LM;
  2408. end
  2409. else
  2410. If dp<mp then
  2411. begin
  2412. d:=values[1];
  2413. m:=values[2];
  2414. end
  2415. else
  2416. begin
  2417. d:=values[2];
  2418. m:=values[1];
  2419. end;
  2420. end;
  2421. if (y >= 0) and (y < 100) and not YearMoreThenTwoDigits then
  2422. begin
  2423. ly := ly - TwoDigitYearCenturyWindow;
  2424. Inc(Y, ly div 100 * 100);
  2425. if (TwoDigitYearCenturyWindow > 0) and (Y < ly) then
  2426. Inc(Y, 100);
  2427. end;
  2428. if not TryEncodeDate(y, m, d, result) then
  2429. errormsg:=SErrInvalidDate;
  2430. end;
  2431. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  2432. Var
  2433. MSg : String;
  2434. begin
  2435. Result:=IntStrToDate(Msg,S,useFormat,Separator);
  2436. If (Msg<>'') then
  2437. Raise EConvertError.Create(Msg);
  2438. end;
  2439. function StrToDate(const S: String; separator : char): TDateTime;
  2440. begin
  2441. result := StrToDate(S,ShortDateFormat,separator)
  2442. end;
  2443. function StrToDate(const S: String): TDateTime;
  2444. begin
  2445. result := StrToDate(S,ShortDateFormat,#0);
  2446. end;
  2447. { StrToTime converts the string S to a TDateTime value
  2448. if S does not represent a valid time value an
  2449. EConvertError will be raised }
  2450. function IntStrToTime(Out ErrorMsg : String; const S: String; Len : integer; separator : char): TDateTime;
  2451. const
  2452. AMPM_None = 0;
  2453. AMPM_AM = 1;
  2454. AMPM_PM = 2;
  2455. tiHour = 0;
  2456. tiMin = 1;
  2457. tiSec = 2;
  2458. tiMSec = 3;
  2459. type
  2460. TTimeValues = array of Word;
  2461. var
  2462. AmPm: integer;
  2463. TimeValues: TTimeValues;
  2464. function SplitElements(out TimeValues: TTimeValues; out AmPm: Integer): Boolean;
  2465. //Strict version. It does not allow #32 as Separator, it will treat it as whitespace always
  2466. const
  2467. Digits = '0123456789';
  2468. var
  2469. Cur, Offset, ElemLen, Err, TimeIndex, FirstSignificantDigit: Integer;
  2470. Value: Integer;
  2471. DigitPending, MSecPending: Boolean;
  2472. AmPmStr: String;
  2473. CurChar: Char;
  2474. I : Integer;
  2475. allowedchars : string;
  2476. begin
  2477. Result := False;
  2478. AmPm := AMPM_None; //No Am or PM in string found yet
  2479. MSecPending := False;
  2480. TimeIndex := 0; //indicating which TTimeValue must be filled next
  2481. For I:=tiHour to tiMSec do
  2482. TimeValues[i]:=0;
  2483. Cur := 1;
  2484. //skip leading blanks
  2485. While (Cur < Len) and (S[Cur] =#32) do Inc(Cur);
  2486. Offset := Cur;
  2487. //First non-blank cannot be Separator or DecimalSeparator
  2488. if (Cur > Len - 1) or (S[Cur] = Separator) or (S[Cur] = Decimalseparator) then
  2489. begin
  2490. // Writeln('Error in sep S[Cur]',S[Cur],' ',separator,' ',GetDecimalSeparator);
  2491. Exit;
  2492. end;
  2493. DigitPending := (Pos(S[Cur],Digits)>0);
  2494. While (Cur <= Len) do
  2495. begin
  2496. //writeln;
  2497. // writeln('Main While loop: Cur = ',Cur,' S[Cur] = "',S[Cur],'" Len = ',Len,' separator : ',Separator);
  2498. CurChar := S[Cur];
  2499. if Pos(CurChar,Digits)>0 then
  2500. begin//Digits
  2501. //HH, MM, SS, or Msec?
  2502. // writeln('Digit: ', CurChar);
  2503. //Digits are only allowed after starting Am/PM or at beginning of string or after Separator
  2504. //and TimeIndex must be <= tiMSec
  2505. //Uncomment "or (#32 = Separator)" and it will allllow #32 as separator
  2506. if (not (DigitPending {or (#32 = Separator)})) or (TimeIndex > tiMSec) then
  2507. begin
  2508. // Writeln('DigitPending',ElemLen);
  2509. Exit;
  2510. end;
  2511. OffSet := Cur;
  2512. if (CurChar <> '0') then FirstSignificantDigit := OffSet else FirstSignificantDigit := -1;
  2513. while (Cur < Len) and (Pos(S[Cur + 1],Digits)>0) do
  2514. begin
  2515. //Mark first Digit that is not '0'
  2516. if (FirstSignificantDigit = -1) and (S[Cur] <> '0') then FirstSignificantDigit := Cur;
  2517. Inc(Cur);
  2518. end;
  2519. if (FirstSignificantDigit = -1) then FirstSignificantDigit := Cur;
  2520. ElemLen := 1+ Cur - FirstSignificantDigit;
  2521. // writeln(' S[FirstSignificantDigit] = ',S[FirstSignificantDigit], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[Offset], ElemLen);
  2522. // writeln(' Cur = ',Cur);
  2523. //this way we know that Val() will never overflow Value !
  2524. if (ElemLen <= 2) or ((ElemLen <= 3) and (TimeIndex = tiMSec) ) then
  2525. begin
  2526. Val(Copy(S,FirstSignificantDigit, ElemLen), Value, Err);
  2527. // writeln(' Value = ',Value,' HH = ',TimeValues[0],' MM = ',TimeValues[1],' SS = ',TimeValues[2],' MSec = ',Timevalues[3]);
  2528. //This is safe now, because we know Value < High(Word)
  2529. TimeValues[TimeIndex] := Value;
  2530. Inc(TimeIndex);
  2531. DigitPending := False;
  2532. end
  2533. else
  2534. begin
  2535. // Writeln('Wrong elemlen: ',ElemLen, ' timeIndex: ',timeindex);
  2536. Exit; //Value to big, so it must be a wrong timestring
  2537. end;
  2538. end//Digits
  2539. else if (CurChar = #32) then
  2540. begin
  2541. //writeln('#32');
  2542. //just skip, but we must adress this, or it will be parsed by either AM/PM or Separator
  2543. end
  2544. else if (CurChar = Separator) then
  2545. begin
  2546. // writeln('Separator ',Separator);
  2547. if DigitPending or (TimeIndex > tiSec) then
  2548. begin
  2549. // Writeln ('DigitPending ',DigitPending,' or (TimeIndex',Timeindex,' > tiSec,', tiSec,')');
  2550. Exit;
  2551. end;
  2552. DigitPending := True;
  2553. MSecPending := False;
  2554. end
  2555. else if (CurChar = DecimalSeparator) then
  2556. begin
  2557. //writeln('DecimalSeparator');
  2558. if DigitPending or MSecPending or (TimeIndex <> tiMSec) then
  2559. begin
  2560. // Writeln('DigitPending ',DigitPending,' or MSecPending ',MSecPending,' (',TimeIndex,',Timeindex, >', tiMSec,' tiSec)');
  2561. Exit;
  2562. end;
  2563. DigitPending := True;
  2564. MSecPending := True;
  2565. end
  2566. else
  2567. begin//AM/PM?
  2568. //None of the above, so this char _must_ be the start of AM/PM string
  2569. //If we already have found AM/PM or we expect a digit then then timestring must be wrong at this point
  2570. //writeln('AM/PM?');
  2571. if (AmPm <> AMPM_None) or DigitPending then
  2572. begin
  2573. // Writeln('AmPm <> AMPM_None) or DigitPending');
  2574. Exit;
  2575. end;
  2576. OffSet := Cur;
  2577. allowedchars:=DecimalSeparator+' ';
  2578. if Separator<>#0 then
  2579. allowedchars:=allowedchars+Separator;
  2580. while (Cur < Len -1) and (Pos(S[Cur + 1],AllowedChars)=0)
  2581. and (Pos(S[Cur + 1],Digits)=0) do Inc(Cur);
  2582. ElemLen := 1 + Cur - OffSet;
  2583. // writeln(' S[Offset] = ',S[1+Offset], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[1+Offset], ElemLen);
  2584. // writeln(' Cur = ',Cur, 'S =',S);
  2585. AmPmStr := Copy(S,1+OffSet, ElemLen);
  2586. // writeln('AmPmStr = ',ampmstr,' (',length(ampmstr),')');
  2587. //We must compare to TimeAMString before hardcoded 'AM' for delphi compatibility
  2588. //Also it is perfectly legal, though insane to have TimeAMString = 'PM' and vice versa
  2589. if (CompareText(AmPmStr, TimeAMString) = 0) then AmPm := AMPM_AM
  2590. else if (CompareText(AmPmStr, TimePMString) = 0) then AmPm := AMPM_PM
  2591. else if (CompareText(AmPmStr, 'AM') = 0) then AmPm := AMPM_AM
  2592. else if (CompareText(AmPmStr, 'PM') = 0) then AmPm := AMPM_PM
  2593. else
  2594. begin
  2595. // Writeln('No timestring ',AmPmStr);
  2596. Exit; //If text does not match any of these, timestring must be wrong;
  2597. end;
  2598. //if AM/PM is at beginning of string, then a digit is mandatory after it
  2599. if (TimeIndex = tiHour) then
  2600. begin
  2601. DigitPending := True;
  2602. end
  2603. //otherwise, no more TimeValues allowed after this
  2604. else
  2605. begin
  2606. TimeIndex := tiMSec + 1;
  2607. DigitPending := False;
  2608. end;
  2609. end;//AM/PM
  2610. Inc(Cur)
  2611. end;//while
  2612. //If we arrive here, parsing the elements has been successfull
  2613. //if not at least Hours specified then input is not valid
  2614. //when am/pm is specified Hour must be <= 12 and not 0
  2615. if (TimeIndex = tiHour) or ((AmPm <> AMPM_None) and ((TimeValues[tiHour] > 12) or (TimeValues[tiHour] = 0))) or DigitPending then
  2616. Exit;
  2617. Result := True;
  2618. end;
  2619. begin
  2620. setlength(timevalues,4);
  2621. if separator = #0 then
  2622. if (TimeSeparator<>#0) then
  2623. separator := TimeSeparator
  2624. else
  2625. separator:=':';
  2626. AmPm := AMPM_None;
  2627. if not SplitElements(TimeValues, AmPm) then
  2628. begin
  2629. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2630. Exit;
  2631. end;
  2632. if (AmPm=AMPM_PM) and (TimeValues[tiHour]<>12) then Inc(TimeValues[tiHour], 12)
  2633. else if (AmPm=AMPM_AM) and (TimeValues[tiHour]=12) then TimeValues[tiHour]:=0;
  2634. // Writeln( TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec]);
  2635. if not TryEncodeTime(TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec], result) Then
  2636. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2637. end ;
  2638. function StrToTime(const s: String; separator : char): TDateTime;
  2639. Var
  2640. Msg : String;
  2641. begin
  2642. Result:=IntStrToTime(Msg,S,Length(S),Separator);
  2643. If (Msg<>'') then
  2644. Raise EConvertError.Create(Msg);
  2645. end;
  2646. function StrToTime(const s: String): TDateTime;
  2647. begin
  2648. result:= StrToTime(s, TimeSeparator);
  2649. end;
  2650. { StrToDateTime converts the string S to a TDateTime value
  2651. if S does not represent a valid date and/or time value
  2652. an EConvertError will be raised }
  2653. function SplitDateTimeStr(DateTimeStr: String; out DateStr, TimeStr: String): Integer;
  2654. { Helper function for StrToDateTime
  2655. Pre-condition
  2656. Date is before Time
  2657. If either Date or Time is omitted then see what fits best, a time or a date (issue #0020522)
  2658. Date and Time are separated by whitespace (space Tab, Linefeed or carriage return)
  2659. FS.DateSeparator can be the same as FS.TimeSeparator (issue #0020522)
  2660. If they are both #32 and TrimWhite(DateTimeStr) contains a #32 a date is assumed.
  2661. Post-condition
  2662. DateStr holds date as string or is empty
  2663. TimeStr holds time as string or is empty
  2664. Result = number of strings returned, 0 = error
  2665. }
  2666. const
  2667. WhiteSpace = #9#10#13#32;
  2668. var
  2669. p: Integer;
  2670. DummyDT: TDateTime;
  2671. begin
  2672. Result := 0;
  2673. DateStr := '';
  2674. TimeStr := '';
  2675. DateTimeStr := Trim(DateTimeStr);
  2676. if Length(DateTimeStr) = 0 then exit;
  2677. if (DateSeparator = #32) and (TimeSeparator = #32) and (Pos(#32, DateTimeStr) > 0) then
  2678. begin
  2679. DateStr:=DateTimeStr;
  2680. {
  2681. Assume a date: dd [mm [yy]].
  2682. Really fancy would be counting the number of whitespace occurrences and decide
  2683. and split accordingly
  2684. }
  2685. Exit(1);
  2686. end;
  2687. p:=1;
  2688. //find separator
  2689. if (DateSeparator<>#32) then
  2690. begin
  2691. while (p<Length(DateTimeStr)) and (not (Pos(DateTimeStr[p+1],WhiteSpace)>0)) do
  2692. Inc(p);
  2693. end
  2694. else
  2695. begin
  2696. p:=Pos(TimeSeparator, DateTimeStr);
  2697. if (p<>0) then
  2698. repeat
  2699. Dec(p);
  2700. until (p=0) or (Pos(DateTimeStr[p],WhiteSpace)>0);
  2701. end;
  2702. //Always fill DateStr, it eases the algorithm later
  2703. if (p=0) then
  2704. p:=Length(DateTimeStr);
  2705. DateStr:=Copy(DateTimeStr,1,p);
  2706. TimeStr:=Trim(Copy(DateTimeStr,p+1,100));
  2707. if (Length(TimeStr)<>0) then
  2708. Result:=2
  2709. else
  2710. begin
  2711. Result:=1; //found 1 string
  2712. // 2 cases when DateTimeStr only contains a time:
  2713. // Date/time separator differ, and string contains a timeseparator
  2714. // Date/time separators are equal, but transformation to date fails.
  2715. if ((DateSeparator<>TimeSeparator) and (Pos(TimeSeparator,DateStr) > 0))
  2716. or ((DateSeparator=TimeSeparator) and (not TryStrToDate(DateStr, DummyDT))) then
  2717. begin
  2718. TimeStr := DateStr;
  2719. DateStr := '';
  2720. end;
  2721. end;
  2722. end;
  2723. function StrToDateTime(const s: String): TDateTime;
  2724. var
  2725. TimeStr, DateStr: String;
  2726. PartsFound: Integer;
  2727. begin
  2728. PartsFound := SplitDateTimeStr(S, DateStr, TimeStr);
  2729. case PartsFound of
  2730. 0: Result:=StrToDate('');
  2731. 1: if (Length(DateStr) > 0) then
  2732. Result := StrToDate(DateStr,ShortDateFormat,DateSeparator)
  2733. else
  2734. Result := StrToTime(TimeStr);
  2735. 2: Result := ComposeDateTime(StrTodate(DateStr,ShortDateFormat,DateSeparator),
  2736. StrToTime(TimeStr));
  2737. end;
  2738. end;
  2739. Function FormatDateTime(const FormatStr: string; const DateTime: TDateTime) : String;
  2740. procedure StoreStr(APos,Len: Integer);
  2741. begin
  2742. // Writeln('StoreStr: ',Result,'+',Copy(FormatStr,APos,Len));
  2743. Result:=Result+Copy(FormatStr,APos,Len);
  2744. end;
  2745. procedure StoreString(const AStr: string);
  2746. begin
  2747. // Writeln('StoreString: ',Result,'+',AStr);
  2748. Result:=Result+AStr;
  2749. end;
  2750. procedure StoreInt(Value, Digits: Integer);
  2751. var
  2752. S: string;
  2753. begin
  2754. S:=IntToStr(Value);
  2755. While (Length(S)<Digits) do
  2756. S:='0'+S;
  2757. StoreString(S);
  2758. end;
  2759. var
  2760. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  2761. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  2762. var
  2763. Token, lastformattoken, prevlasttoken: char;
  2764. Count: integer;
  2765. Clock12: boolean;
  2766. tmp: integer;
  2767. isInterval: Boolean;
  2768. P,FormatCurrent,FormatEnd : Integer;
  2769. begin
  2770. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  2771. Exit;
  2772. FormatCurrent := 1;
  2773. FormatEnd := Length(FormatStr);
  2774. Clock12 := false;
  2775. isInterval := false;
  2776. // look for unquoted 12-hour clock token
  2777. P:=1;
  2778. while P<=FormatEnd do
  2779. begin
  2780. Token := FormatStr[P];
  2781. case Token of
  2782. '''', '"':
  2783. begin
  2784. Inc(P);
  2785. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2786. Inc(P);
  2787. end;
  2788. 'A', 'a':
  2789. begin
  2790. if (CompareText(Copy(FormatStr,P,3),'A/P')=0) or
  2791. (CompareText(Copy(FormatStr,P,4),'AMPM')=0) or
  2792. (CompareText(Copy(FormatStr,P,5),'AM/PM')=0) then
  2793. begin
  2794. Clock12 := true;
  2795. break;
  2796. end;
  2797. end;
  2798. end; // case
  2799. Inc(P);
  2800. end ;
  2801. token := #255;
  2802. lastformattoken := ' ';
  2803. prevlasttoken := 'H';
  2804. while FormatCurrent <= FormatEnd do
  2805. begin
  2806. Token := UpperCase(FormatStr[FormatCurrent])[1];
  2807. // Writeln('Treating token at pos ',FormatCurrent,', : ',Token,' (',FormatStr,')');
  2808. Count := 1;
  2809. P := FormatCurrent + 1;
  2810. case Token of
  2811. '''', '"':
  2812. begin
  2813. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2814. Inc(P);
  2815. Inc(P);
  2816. Count := P - FormatCurrent;
  2817. StoreStr(FormatCurrent + 1, Count - 2);
  2818. end ;
  2819. 'A':
  2820. begin
  2821. if CompareText(Copy(FormatStr,FormatCurrent,4), 'AMPM') = 0 then
  2822. begin
  2823. Count := 4;
  2824. if Hour < 12 then
  2825. StoreString(TimeAMString)
  2826. else
  2827. StoreString(TimePMString);
  2828. end
  2829. else if CompareText(Copy(FormatStr,FormatCurrent,5), 'AM/PM') = 0 then
  2830. begin
  2831. Count := 5;
  2832. if Hour < 12 then StoreStr(FormatCurrent, 2)
  2833. else StoreStr(FormatCurrent+3, 2);
  2834. end
  2835. else if CompareText(Copy(FormatStr,FormatCurrent,3), 'A/P') = 0 then
  2836. begin
  2837. Count := 3;
  2838. if Hour < 12 then StoreStr(FormatCurrent, 1)
  2839. else StoreStr(FormatCurrent+2, 1);
  2840. end
  2841. else
  2842. raise EConvertError.Create('Illegal character in format string');
  2843. end ;
  2844. '/':
  2845. begin
  2846. // Writeln('Detected date separator');
  2847. StoreString(DateSeparator);
  2848. end;
  2849. ':': StoreString(TimeSeparator);
  2850. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' :
  2851. begin
  2852. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2853. while (P <= FormatEnd) and (UpperCase(FormatStr[P]) = Token) do
  2854. Inc(P);
  2855. Count := P - FormatCurrent;
  2856. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2857. case Token of
  2858. ' ': StoreStr(FormatCurrent, Count);
  2859. 'Y': begin
  2860. if Count > 2 then
  2861. StoreInt(Year, 4)
  2862. else
  2863. StoreInt(Year mod 100, 2);
  2864. end;
  2865. 'M': begin
  2866. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  2867. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2868. else
  2869. if (lastformattoken = 'H') or TimeFlag then
  2870. begin
  2871. if Count = 1 then
  2872. StoreInt(Minute, 0)
  2873. else
  2874. StoreInt(Minute, 2);
  2875. end
  2876. else
  2877. begin
  2878. case Count of
  2879. 1: StoreInt(Month, 0);
  2880. 2: StoreInt(Month, 2);
  2881. 3: StoreString(ShortMonthNames[Month]);
  2882. else
  2883. StoreString(LongMonthNames[Month]);
  2884. end;
  2885. end;
  2886. end;
  2887. 'D': begin
  2888. case Count of
  2889. 1: StoreInt(Day, 0);
  2890. 2: StoreInt(Day, 2);
  2891. 3: StoreString(ShortDayNames[DayOfWeek]);
  2892. 4: StoreString(LongDayNames[DayOfWeek]);
  2893. 5: StoreFormat(ShortDateFormat, Nesting+1, False);
  2894. else
  2895. StoreFormat(LongDateFormat, Nesting+1, False);
  2896. end ;
  2897. end ;
  2898. 'H':
  2899. if isInterval then
  2900. StoreInt(Hour + trunc(abs(DateTime))*24, 0)
  2901. else
  2902. if Clock12 then
  2903. begin
  2904. tmp := hour mod 12;
  2905. if tmp=0 then tmp:=12;
  2906. if Count = 1 then
  2907. StoreInt(tmp, 0)
  2908. else
  2909. StoreInt(tmp, 2);
  2910. end
  2911. else begin
  2912. if Count = 1 then
  2913. StoreInt(Hour, 0)
  2914. else
  2915. StoreInt(Hour, 2);
  2916. end;
  2917. 'N': if isInterval then
  2918. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2919. else
  2920. if Count = 1 then
  2921. StoreInt(Minute, 0)
  2922. else
  2923. StoreInt(Minute, 2);
  2924. 'S': if isInterval then
  2925. StoreInt(Second + (Minute + (Hour + trunc(abs(DateTime))*24)*60)*60, 0)
  2926. else
  2927. if Count = 1 then
  2928. StoreInt(Second, 0)
  2929. else
  2930. StoreInt(Second, 2);
  2931. 'Z': if Count = 1 then
  2932. StoreInt(MilliSecond, 0)
  2933. else
  2934. StoreInt(MilliSecond, 3);
  2935. 'T': if Count = 1 then
  2936. StoreFormat(ShortTimeFormat, Nesting+1, True)
  2937. else
  2938. StoreFormat(LongTimeFormat, Nesting+1, True);
  2939. 'C': begin
  2940. StoreFormat(ShortDateFormat, Nesting+1, False);
  2941. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  2942. begin
  2943. StoreString(' ');
  2944. StoreFormat(LongTimeFormat, Nesting+1, True);
  2945. end;
  2946. end;
  2947. 'F': begin
  2948. StoreFormat(ShortDateFormat, Nesting+1, False);
  2949. StoreString(' ');
  2950. StoreFormat(LongTimeFormat, Nesting+1, True);
  2951. end;
  2952. end;
  2953. prevlasttoken := lastformattoken;
  2954. lastformattoken := token;
  2955. end;
  2956. else
  2957. StoreString(Token);
  2958. end ;
  2959. Inc(FormatCurrent, Count);
  2960. end;
  2961. end;
  2962. begin
  2963. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  2964. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  2965. // Writeln(DateTime,'->',Year,',', Month, ',',Day, ',',DayOfWeek,',',Hour, ',',Minute, ',',Second, ',',MilliSecond);
  2966. if FormatStr <> '' then
  2967. StoreFormat(FormatStr, 0, False)
  2968. else
  2969. StoreFormat('C', 0, False);
  2970. end ;
  2971. function CurrentYear: Word;
  2972. begin
  2973. Result:=TJSDate.New().FullYear;
  2974. end;
  2975. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  2976. begin
  2977. Result:=TryStrToDate(S,Value,ShortDateFormat,#0);
  2978. end;
  2979. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  2980. begin
  2981. Result:=TryStrToDate(S,Value,ShortDateFormat,Separator);
  2982. end;
  2983. function TryStrToDate(const S: String; out Value: TDateTime;
  2984. const useformat : string; separator : char = #0): Boolean;
  2985. Var
  2986. Msg : String;
  2987. begin
  2988. Result:=Length(S)<>0;
  2989. If Result then
  2990. begin
  2991. Value:=IntStrToDate(Msg,S,useformat,Separator);
  2992. Result:=(Msg='');
  2993. end;
  2994. end;
  2995. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  2996. Var
  2997. Msg : String;
  2998. begin
  2999. Result:=Length(S)<>0;
  3000. If Result then
  3001. begin
  3002. Value:=IntStrToTime(Msg,S,Length(S),Separator);
  3003. Result:=(Msg='');
  3004. end;
  3005. end;
  3006. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  3007. begin
  3008. result:=TryStrToTime(S,Value,#0);
  3009. end;
  3010. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  3011. var
  3012. I: integer;
  3013. dtdate, dttime :TDateTime;
  3014. begin
  3015. result:=false;
  3016. I:=Pos(TimeSeparator,S);
  3017. If (I>0) then
  3018. begin
  3019. While (I>0) and (S[I]<>' ') do
  3020. Dec(I);
  3021. If I>0 then
  3022. begin
  3023. if not TryStrToDate(Copy(S,1,I-1),dtdate) then
  3024. exit;
  3025. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime) then
  3026. exit;
  3027. Value:=ComposeDateTime(dtdate,dttime);
  3028. result:=true;
  3029. end
  3030. else
  3031. result:=TryStrToTime(s,Value);
  3032. end
  3033. else
  3034. result:=TryStrToDate(s,Value);
  3035. end;
  3036. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3037. begin
  3038. result := StrToDateDef(S,DefValue,#0);
  3039. end;
  3040. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3041. begin
  3042. result := StrToTimeDef(S,DefValue,#0);
  3043. end;
  3044. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3045. begin
  3046. if not TryStrToDateTime(s,Result) Then
  3047. result:=defvalue;
  3048. end;
  3049. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  3050. begin
  3051. if not TryStrToDate(s,Result, separator) Then
  3052. result:=defvalue;
  3053. end;
  3054. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  3055. begin
  3056. if not TryStrToTime(s,Result, separator) Then
  3057. result:=defvalue;
  3058. end;
  3059. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);
  3060. begin
  3061. dati:= ComposeDateTime(dati, newtime);
  3062. end;
  3063. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  3064. var
  3065. tmp : TDateTime;
  3066. begin
  3067. tmp:=NewDate;
  3068. ReplaceTime(tmp,DateTime);
  3069. DateTime:=tmp;
  3070. end;
  3071. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  3072. begin
  3073. If (Value<MinDateTime) or (Value>MaxDateTime) then
  3074. Raise EConvertError.CreateFmt (SInvalidDateTime,[FloatToStr(Value)]);
  3075. Result:=Value;
  3076. end;
  3077. function FloattoCurr(const Value: Extended): Currency;
  3078. begin
  3079. if not TryFloatToCurr(Value, Result) then
  3080. Raise EConvertError.CreateFmt(SInvalidCurrency, [FloatToStr(Value)]);
  3081. end;
  3082. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  3083. begin
  3084. Result:=(Value>=MinCurrency) and (Value<=MaxCurrency);
  3085. if Result then
  3086. AResult := Value;
  3087. end;
  3088. function CurrToStr(Value: Currency): string;
  3089. begin
  3090. Result:=FloatToStrF(Value,ffGeneral,-1,0);
  3091. end;
  3092. (*
  3093. function CurrToStr(Value: Currency; const FormatSettings: TFormatSettings): string;
  3094. begin
  3095. end;
  3096. *)
  3097. function StrToCurr(const S: string): Currency;
  3098. begin
  3099. if not TryStrToCurr(S,Result) then
  3100. Raise EConvertError.createfmt(SInvalidCurrency,[S]);
  3101. end;
  3102. (*
  3103. function StrToCurr(const S: string; const FormatSettings: TFormatSettings): Currency;
  3104. begin
  3105. end;
  3106. *)
  3107. function TryStrToCurr(const S: string; out Value: Currency): Boolean;
  3108. Var
  3109. D : Double;
  3110. begin
  3111. Result:=TryStrToFloat(S,D);
  3112. if Result then
  3113. Value:=D;
  3114. end;
  3115. (*
  3116. function TryStrToCurr(const S: string; out Value: Currency; const FormatSettings: TFormatSettings): Boolean;
  3117. begin
  3118. end;
  3119. *)
  3120. function StrToCurrDef(const S: string; Default: Currency): Currency;
  3121. Var
  3122. R : Currency;
  3123. begin
  3124. if TryStrToCurr(S,R) then
  3125. Result:=R
  3126. else
  3127. Result:=Default;
  3128. end;
  3129. (*
  3130. function StrToCurrDef(const S: string; Default: Currency; const FormatSettings: TFormatSettings): Currency;
  3131. begin
  3132. end;
  3133. *)
  3134. { ---------------------------------------------------------------------
  3135. Interface related
  3136. ---------------------------------------------------------------------}
  3137. function Supports(const Instance: IInterface; const AClass: TClass; out Obj
  3138. ): Boolean;
  3139. begin
  3140. Result := (Instance<>nil) and (Instance.QueryInterface(IObjectInstance,Obj)=S_OK)
  3141. and (TObject(Obj).InheritsFrom(AClass));
  3142. end;
  3143. function Supports(const Instance: IInterface; const IID: TGUID; out Intf
  3144. ): Boolean;
  3145. begin
  3146. Result:=(Instance<>nil) and (Instance.QueryInterface(IID,Intf)=S_OK);
  3147. end;
  3148. function Supports(const Instance: TObject; const IID: TGUID; out Intf
  3149. ): Boolean;
  3150. begin
  3151. Result:=(Instance<>nil) and Instance.GetInterface(IID,Intf);
  3152. end;
  3153. function Supports(const Instance: TObject; const IID: TGuidString; out Intf
  3154. ): Boolean;
  3155. begin
  3156. Result:=(Instance<>nil) and Instance.GetInterfaceByStr(IID,Intf);
  3157. end;
  3158. function Supports(const Instance: IInterface; const AClass: TClass): Boolean;
  3159. var
  3160. Temp: TObject;
  3161. begin
  3162. Result:=Supports(Instance,AClass,Temp);
  3163. end;
  3164. function Supports(const Instance: IInterface; const IID: TGUID): Boolean;
  3165. var
  3166. Temp: IInterface;
  3167. begin
  3168. Result:=Supports(Instance,IID,Temp);
  3169. end;
  3170. function Supports(const Instance: TObject; const IID: TGUID): 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 Instance: TObject; const IID: TGuidString): Boolean;
  3180. var
  3181. Temp: TJSObject;
  3182. begin
  3183. Result:=Supports(Instance,IID,Temp);
  3184. asm
  3185. if (Temp && Temp.$kind==='com') Temp._Release();
  3186. end;
  3187. end;
  3188. function Supports(const AClass: TClass; const IID: TGUID): Boolean;
  3189. var
  3190. maps: JSValue;
  3191. begin
  3192. if AClass=nil then exit(false);
  3193. maps := TJSObject(AClass)['$intfmaps'];
  3194. if not maps then exit(false);
  3195. if TJSObject(maps)[GUIDToString(IID)] then exit(true);
  3196. Result:=false;
  3197. end;
  3198. function Supports(const AClass: TClass; const IID: TGuidString): Boolean;
  3199. var
  3200. maps: JSValue;
  3201. begin
  3202. if AClass=nil then exit(false);
  3203. maps := TJSObject(AClass)['$intfmaps'];
  3204. if not maps then exit(false);
  3205. if TJSObject(maps)[uppercase(IID)] then exit(true);
  3206. Result:=false;
  3207. end;
  3208. function TryStringToGUID(const s: string; out Guid: TGUID): Boolean;
  3209. var
  3210. re: TJSRegexp;
  3211. begin
  3212. if Length(s)<>38 then Exit(False);
  3213. 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}\}$');
  3214. Result:=re.test(s);
  3215. if not Result then
  3216. begin
  3217. Guid.D1:=0;
  3218. exit;
  3219. end;
  3220. asm
  3221. rtl.strToGUIDR(s,Guid.get());
  3222. end;
  3223. Result:=true;
  3224. end;
  3225. function StringToGUID(const S: string): TGUID;
  3226. begin
  3227. if not TryStringToGUID(S, Result) then
  3228. raise EConvertError.CreateFmt(SInvalidGUID, [S]);
  3229. end;
  3230. function GUIDToString(const guid: TGUID): string;
  3231. begin
  3232. Result:=System.GUIDToString(guid);
  3233. end;
  3234. function IsEqualGUID(const guid1, guid2: TGUID): Boolean;
  3235. var
  3236. i: integer;
  3237. begin
  3238. if (guid1.D1<>guid2.D1) or (guid1.D2<>guid2.D2) or (guid1.D3<>guid2.D3) then
  3239. exit(false);
  3240. for i:=0 to 7 do if guid1.D4[i]<>guid2.D4[i] then exit(false);
  3241. Result:=true;
  3242. end;
  3243. function GuidCase(const guid: TGUID; const List: array of TGuid): Integer;
  3244. begin
  3245. for Result := High(List) downto 0 do
  3246. if IsEqualGUID(guid, List[Result]) then
  3247. Exit;
  3248. Result := -1;
  3249. end;
  3250. { ---------------------------------------------------------------------
  3251. Integer/Ordinal related
  3252. ---------------------------------------------------------------------}
  3253. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  3254. Var
  3255. NI : NativeInt;
  3256. begin
  3257. Result:=TryStrToInt(S,NI);
  3258. if Result then
  3259. res:=NI;
  3260. end;
  3261. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  3262. Var
  3263. Radix : Integer = 10;
  3264. N : String;
  3265. J : JSValue;
  3266. begin
  3267. N:=S;
  3268. case Copy(N,1,1) of
  3269. '$': Radix:=16;
  3270. '&': Radix:=8;
  3271. '%': Radix:=2;
  3272. end;
  3273. If Radix<>10 then
  3274. Delete(N,1,1);
  3275. J:=parseInt(N,Radix);
  3276. Result:=Not jsIsNan(j);
  3277. if Result then
  3278. res:=NativeInt(J);
  3279. end;
  3280. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  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 StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  3290. Var
  3291. R : NativeInt;
  3292. begin
  3293. if TryStrToInt(S,R) then
  3294. Result:=R
  3295. else
  3296. Result:=aDef;
  3297. end;
  3298. Function StrToInt(const S : String) : Integer;
  3299. Var
  3300. R : NativeInt;
  3301. begin
  3302. if not TryStrToInt(S,R) then
  3303. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3304. Result:=R;
  3305. end;
  3306. Function StrToNativeInt(const S : String) : NativeInt;
  3307. begin
  3308. if not TryStrToInt(S,Result) then
  3309. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3310. end;
  3311. Function StrToInt64(const S : String) : NativeLargeInt;
  3312. Var
  3313. N : NativeInt;
  3314. begin
  3315. if not TryStrToInt(S,N) then
  3316. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3317. Result:=N;
  3318. end;
  3319. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  3320. Var
  3321. R : nativeint;
  3322. begin
  3323. Result:=TryStrToInt(S,R);
  3324. If Result then
  3325. Res:=R;
  3326. end;
  3327. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  3328. begin
  3329. if TryStrToInt64(S,Result) then
  3330. Result:=ADefault;
  3331. end;
  3332. Function StrToQWord(const S : String) : NativeLargeUInt;
  3333. Var
  3334. N : NativeInt;
  3335. begin
  3336. if (not TryStrToInt(S,N)) or (N<0) then
  3337. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3338. Result:=N;
  3339. end;
  3340. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  3341. Var
  3342. R : nativeint;
  3343. begin
  3344. Result:=TryStrToInt(S,R) and (R>=0);
  3345. If Result then
  3346. Res:=R;
  3347. end;
  3348. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3349. begin
  3350. if Not TryStrToQword(S,Result) then
  3351. Result:=ADefault;
  3352. end;
  3353. Function StrToUInt64(const S : String) : NativeLargeUInt;
  3354. Var
  3355. N : NativeInt;
  3356. begin
  3357. if (not TryStrToInt(S,N)) or (N<0) then
  3358. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3359. Result:=N;
  3360. end;
  3361. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  3362. Var
  3363. R : nativeint;
  3364. begin
  3365. Result:=TryStrToInt(S,R) and (R>=0);
  3366. If Result then
  3367. Res:=R;
  3368. end;
  3369. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3370. begin
  3371. if Not TryStrToUInt64(S,Result) then
  3372. Result:=ADefault;
  3373. end;
  3374. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  3375. Var
  3376. R : nativeint;
  3377. begin
  3378. Result:=TryStrToInt(S,R) and (R>=0) and (R<=DWord($FFFFFFFF));
  3379. If Result then
  3380. Res:=R;
  3381. end;
  3382. Function StrToDWord(const S : String) : DWord;
  3383. begin
  3384. if not TryStrToDWord(S,Result) then
  3385. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3386. end;
  3387. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  3388. begin
  3389. if Not TryStrToDWord(S,Result) then
  3390. Result:=ADefault;
  3391. end;
  3392. function IntToHex(Value: NativeInt; Digits: integer): string;
  3393. const
  3394. HexDigits = '0123456789ABCDEF';
  3395. begin
  3396. If Digits=0 then
  3397. Digits:=1;
  3398. Result:='';
  3399. While Value>0 do
  3400. begin
  3401. result:=HexDigits[(value and 15)+1]+Result;
  3402. value := value shr 4;
  3403. end ;
  3404. while (Length(Result)<Digits) do
  3405. Result:='0'+Result;
  3406. end;
  3407. { TFormatSettings }
  3408. function TFormatSettings.GetCurrencyDecimals: Byte;
  3409. begin
  3410. Result:=Sysutils.CurrencyDecimals;
  3411. end;
  3412. function TFormatSettings.GetCurrencyFormat: Byte;
  3413. begin
  3414. Result:=Sysutils.CurrencyFormat;
  3415. end;
  3416. function TFormatSettings.GetCurrencyString: String;
  3417. begin
  3418. Result:=Sysutils.CurrencyString;
  3419. end;
  3420. function TFormatSettings.GetDateSeparator: char;
  3421. begin
  3422. Result := SysUtils.DateSeparator;
  3423. end;
  3424. function TFormatSettings.GetDecimalSeparator: string;
  3425. begin
  3426. Result := SysUtils.DecimalSeparator;
  3427. end;
  3428. function TFormatSettings.GetLongDateFormat: string;
  3429. begin
  3430. Result := SysUtils.LongDateFormat;
  3431. end;
  3432. function TFormatSettings.GetLongDayNames: TDayNames;
  3433. begin
  3434. Result:=Sysutils.LongDayNames;
  3435. end;
  3436. function TFormatSettings.GetLongMonthNames: TMonthNames;
  3437. begin
  3438. Result:=Sysutils.LongMonthNames;
  3439. end;
  3440. function TFormatSettings.GetLongTimeFormat: string;
  3441. begin
  3442. Result := SysUtils.LongTimeFormat;
  3443. end;
  3444. function TFormatSettings.GetNegCurrFormat: Byte;
  3445. begin
  3446. Result:=Sysutils.NegCurrFormat;
  3447. end;
  3448. function TFormatSettings.GetShortDateFormat: string;
  3449. begin
  3450. Result := SysUtils.ShortDateFormat;
  3451. end;
  3452. function TFormatSettings.GetShortDayNames: TDayNames;
  3453. begin
  3454. Result:=Sysutils.ShortDayNames;
  3455. end;
  3456. function TFormatSettings.GetShortMonthNames: TMonthNames;
  3457. begin
  3458. Result:=Sysutils.ShortMonthNames;
  3459. end;
  3460. function TFormatSettings.GetShortTimeFormat: string;
  3461. begin
  3462. Result := SysUtils.ShortTimeFormat;
  3463. end;
  3464. function TFormatSettings.GetThousandSeparator: string;
  3465. begin
  3466. Result := SysUtils.ThousandSeparator;
  3467. end;
  3468. function TFormatSettings.GetTimeAMString: string;
  3469. begin
  3470. Result := SysUtils.TimeAMString;
  3471. end;
  3472. function TFormatSettings.GetTimePMString: string;
  3473. begin
  3474. Result := SysUtils.TimePMString;
  3475. end;
  3476. function TFormatSettings.GetTimeSeparator: char;
  3477. begin
  3478. Result := SysUtils.TimeSeparator;
  3479. end;
  3480. procedure TFormatSettings.SetCurrencyFormat(AValue: Byte);
  3481. begin
  3482. Sysutils.CurrencyFormat:=AValue;
  3483. end;
  3484. procedure TFormatSettings.SetCurrencyString(AValue: String);
  3485. begin
  3486. Sysutils.CurrencyString:=AValue;
  3487. end;
  3488. procedure TFormatSettings.SetDateSeparator(const Value: char);
  3489. begin
  3490. SysUtils.DateSeparator := Value;
  3491. end;
  3492. procedure TFormatSettings.SetDecimalSeparator(const Value: string);
  3493. begin
  3494. SysUtils.DecimalSeparator := Value;
  3495. end;
  3496. procedure TFormatSettings.SetLongDateFormat(const Value: string);
  3497. begin
  3498. SysUtils.LongDateFormat := Value;
  3499. end;
  3500. procedure TFormatSettings.SetLongDayNames(AValue: TDayNames);
  3501. begin
  3502. SysUtils.LongDayNames:=AValue;
  3503. end;
  3504. procedure TFormatSettings.SetLongMonthNames(AValue: TMonthNames);
  3505. begin
  3506. SysUtils.LongMonthNames:=AValue;
  3507. end;
  3508. procedure TFormatSettings.SetLongTimeFormat(const Value: string);
  3509. begin
  3510. SysUtils.LongTimeFormat := Value;
  3511. end;
  3512. procedure TFormatSettings.SetNegCurrFormat(AValue: Byte);
  3513. begin
  3514. Sysutils.NegCurrFormat:=AValue;
  3515. end;
  3516. procedure TFormatSettings.SetShortDateFormat(const Value: string);
  3517. begin
  3518. SysUtils.ShortDateFormat := Value;
  3519. end;
  3520. procedure TFormatSettings.SetShortDayNames(AValue: TDayNames);
  3521. begin
  3522. SysUtils.ShortDayNames:=AValue;
  3523. end;
  3524. procedure TFormatSettings.SetShortMonthNames(AValue: TMonthNames);
  3525. begin
  3526. SysUtils.ShortMonthNames:=AValue;
  3527. end;
  3528. procedure TFormatSettings.SetShortTimeFormat(const Value: string);
  3529. begin
  3530. SysUtils.ShortTimeFormat := Value;
  3531. end;
  3532. procedure TFormatSettings.SetCurrencyDecimals(AValue: Byte);
  3533. begin
  3534. Sysutils.CurrencyDecimals:=aValue;
  3535. end;
  3536. procedure TFormatSettings.SetThousandSeparator(const Value: string);
  3537. begin
  3538. SysUtils.ThousandSeparator := Value;
  3539. end;
  3540. procedure TFormatSettings.SetTimeAMString(const Value: string);
  3541. begin
  3542. SysUtils.TimeAMString := Value;
  3543. end;
  3544. procedure TFormatSettings.SetTimePMString(const Value: string);
  3545. begin
  3546. SysUtils.TimePMString := Value;
  3547. end;
  3548. procedure TFormatSettings.SetTimeSeparator(const Value: char);
  3549. begin
  3550. SysUtils.TimeSeparator := Value;
  3551. end;
  3552. initialization
  3553. FormatSettings := TFormatSettings.Create;
  3554. end.