sysutils.pas 109 KB

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