sysutils.pas 108 KB

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