sysutils.pas 110 KB

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