sysutils.pas 108 KB

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