sysutils.pas 118 KB

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