sysutils.pas 118 KB

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