sysutils.pas 110 KB

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