sysutils.pas 118 KB

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