sysutils.pas 118 KB

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