sysutils.pas 108 KB

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