sysutils.pas 118 KB

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