sysutils.pas 108 KB

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