sysutils.pas 118 KB

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