Quick.Commons.pas 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. { ***************************************************************************
  2. Copyright (c) 2016-2020 Kike Pérez
  3. Unit : Quick.Commons
  4. Description : Common functions
  5. Author : Kike Pérez
  6. Version : 2.0
  7. Created : 14/07/2017
  8. Modified : 06/08/2020
  9. This file is part of QuickLib: https://github.com/exilon/QuickLib
  10. ***************************************************************************
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. *************************************************************************** }
  21. unit Quick.Commons;
  22. {$i QuickLib.inc}
  23. interface
  24. uses
  25. Classes,
  26. SysUtils,
  27. Types,
  28. {$IFDEF MSWINDOWS}
  29. Windows,
  30. ShlObj,
  31. {$ENDIF MSWINDOWS}
  32. {$IFDEF FPC}
  33. Quick.Files,
  34. {$IFDEF LINUX}
  35. FileInfo,
  36. {$ENDIF}
  37. {$ELSE}
  38. IOUtils,
  39. {$ENDIF}
  40. {$IFDEF ANDROID}
  41. Androidapi.JNI.Os,
  42. Androidapi.Helpers,
  43. Androidapi.JNI.JavaTypes,
  44. Androidapi.JNI.GraphicsContentViewText,
  45. {$ENDIF}
  46. {$IFDEF IOS}
  47. iOSapi.UIKit,
  48. Posix.SysSysctl,
  49. Posix.StdDef,
  50. iOSapi.Foundation,
  51. Macapi.ObjectiveC,
  52. Macapi.Helpers,
  53. {$ENDIF}
  54. {$IFDEF OSX}
  55. Macapi.Foundation,
  56. Macapi.Helpers,
  57. FMX.Helpers.Mac,
  58. Macapi.ObjectiveC,
  59. {$ENDIF}
  60. {$IFDEF POSIX}
  61. Posix.Unistd,
  62. {$ENDIF}
  63. DateUtils;
  64. type
  65. TLogEventType = (etInfo, etSuccess, etWarning, etError, etDebug, etDone, etTrace, etCritical, etException);
  66. TLogVerbose = set of TLogEventType;
  67. const
  68. LOG_ONLYERRORS = [etInfo,etError];
  69. LOG_ERRORSANDWARNINGS = [etInfo,etWarning,etError];
  70. LOG_TRACE = [etInfo,etError,etWarning,etTrace];
  71. LOG_ALL = [etInfo, etSuccess, etWarning, etError, etDebug, etDone, etTrace, etCritical, etException];
  72. LOG_DEBUG = [etInfo,etSuccess,etWarning,etError,etDebug];
  73. {$IFDEF DELPHIXE7_UP}
  74. EventStr : array of string = ['INFO','SUCC','WARN','ERROR','DEBUG','TRACE'];
  75. {$ELSE}
  76. EventStr : array[0..5] of string = ('INFO','SUCC','WARN','ERROR','DEBUG','TRACE');
  77. {$ENDIF}
  78. type
  79. TPasswordComplexity = set of (pfIncludeNumbers,pfIncludeSigns);
  80. TEnvironmentPath = record
  81. EXEPATH : string;
  82. {$IFDEF MSWINDOWS}
  83. WINDOWS : string;
  84. SYSTEM : string;
  85. PROGRAMFILES : string;
  86. COMMONFILES : string;
  87. HOMEDRIVE : string;
  88. TEMP : string;
  89. USERPROFILE : string;
  90. INSTDRIVE : string;
  91. DESKTOP : string;
  92. STARTMENU : string;
  93. DESKTOP_ALLUSERS : string;
  94. STARTMENU_ALLUSERS : string;
  95. STARTUP : string;
  96. APPDATA : String;
  97. PROGRAMDATA : string;
  98. ALLUSERSPROFILE : string;
  99. {$ENDIF MSWINDOWS}
  100. end;
  101. {$IFNDEF FPC}
  102. TFileHelper = record helper for TFile
  103. {$IF DEFINED(MSWINDOWS) OR DEFINED(DELPHILINUX)}
  104. class function IsInUse(const FileName : string) : Boolean; static;
  105. {$ENDIF}
  106. class function GetSize(const FileName: String): Int64; static;
  107. end;
  108. TDirectoryHelper = record helper for TDirectory
  109. class function GetSize(const Path: String): Int64; static;
  110. end;
  111. {$ENDIF}
  112. {$IFDEF FPC}
  113. {$IFDEF LINUX}
  114. UINT = cardinal;
  115. {$ENDIF}
  116. PLASTINPUTINFO = ^LASTINPUTINFO;
  117. tagLASTINPUTINFO = record
  118. cbSize: UINT;
  119. dwTime: DWORD;
  120. end;
  121. LASTINPUTINFO = tagLASTINPUTINFO;
  122. TLastInputInfo = LASTINPUTINFO;
  123. type
  124. TCmdLineSwitchType = (clstValueNextParam, clstValueAppended);
  125. TCmdLineSwitchTypes = set of TCmdLineSwitchType;
  126. {$ENDIF}
  127. TCounter = record
  128. private
  129. fMaxValue : Integer;
  130. fCurrentValue : Integer;
  131. public
  132. property MaxValue : Integer read fMaxValue;
  133. procedure Init(aMaxValue : Integer);
  134. function Count : Integer;
  135. function CountIs(aValue : Integer) : Boolean;
  136. function Check : Boolean;
  137. procedure Reset;
  138. end;
  139. TTimeCounter = record
  140. private
  141. fCurrentTime : TDateTime;
  142. fDoneEvery : Integer;
  143. public
  144. property DoneEvery : Integer read fDoneEvery;
  145. procedure Init(MillisecondsToReach : Integer);
  146. function Check : Boolean;
  147. procedure Reset;
  148. end;
  149. {$IFNDEF FPC}
  150. {$IFNDEF DELPHIXE7_UP}
  151. TArrayUtil<T> = class
  152. class procedure Delete(var aArray : TArray<T>; aIndex : Integer);
  153. end;
  154. {$ENDIF}
  155. TArrayOfStringHelper = record helper for TArray<string>
  156. public
  157. function Any : Boolean; overload;
  158. function Any(const aValue : string) : Boolean; overload;
  159. function Add(const aValue : string) : Integer;
  160. function AddIfNotExists(const aValue : string; aCaseSense : Boolean = False) : Integer;
  161. function Remove(const aValue : string) : Boolean;
  162. function Exists(const aValue : string) : Boolean;
  163. function Count : Integer;
  164. end;
  165. TDelegate<T> = reference to procedure(Value : T);
  166. {$ENDIF}
  167. TPairItem = record
  168. Name : string;
  169. Value : string;
  170. constructor Create(const aName, aValue : string);
  171. end;
  172. TPairList = class
  173. type
  174. TPairEnumerator = class
  175. private
  176. fArray : ^TArray<TPairItem>;
  177. fIndex : Integer;
  178. function GetCurrent: TPairItem;
  179. public
  180. constructor Create(var aArray: TArray<TPairItem>);
  181. property Current : TPairItem read GetCurrent;
  182. function MoveNext: Boolean;
  183. end;
  184. private
  185. fItems : TArray<TPairItem>;
  186. public
  187. function GetEnumerator : TPairEnumerator;
  188. function GetValue(const aName : string) : string;
  189. function GetPair(const aName : string) : TPairItem;
  190. function Add(aPair : TPairItem) : Integer; overload;
  191. function Add(const aName, aValue : string) : Integer; overload;
  192. procedure AddOrUpdate(const aName, aValue : string);
  193. function Exists(const aName : string) : Boolean;
  194. function Remove(const aName : string) : Boolean;
  195. function Count : Integer;
  196. property Items[const aName : string] : string read GetValue write AddOrUpdate;
  197. function ToArray : TArray<TPairItem>;
  198. procedure FromArray(aValue : TArray<TPairItem>);
  199. procedure Clear;
  200. end;
  201. EEnvironmentPath = class(Exception);
  202. EShellError = class(Exception);
  203. //generates a random password with complexity options
  204. function RandomPassword(const PasswordLength : Integer; Complexity : TPasswordComplexity = [pfIncludeNumbers,pfIncludeSigns]) : string;
  205. //generates a random string
  206. function RandomString(const aLength: Integer) : string;
  207. //extracts file extension from a filename
  208. function ExtractFileNameWithoutExt(const FileName: string): string;
  209. //converts a Unix path to Windows path
  210. function UnixToWindowsPath(const UnixPath: string): string;
  211. //converts a Windows path to Unix path
  212. function WindowsToUnixPath(const WindowsPath: string): string;
  213. //corrects malformed urls
  214. function CorrectURLPath(cUrl : string) : string;
  215. //get typical environment paths as temp, desktop, etc
  216. procedure GetEnvironmentPaths;
  217. {$IFDEF MSWINDOWS}
  218. function GetSpecialFolderPath(folderID : Integer) : string;
  219. //checks if running on a 64bit OS
  220. function Is64bitOS : Boolean;
  221. //checks if is a console app
  222. function IsConsole : Boolean;
  223. function HasConsoleOutput : Boolean;
  224. //checks if compiled in debug mode
  225. {$ENDIF}
  226. function IsDebug : Boolean;
  227. {$IFDEF MSWINDOWS}
  228. //checks if running as a service
  229. function IsService : Boolean;
  230. //gets number of seconds without user interaction (mouse, keyboard)
  231. function SecondsIdle: DWord;
  232. //frees process memory not needed
  233. procedure FreeUnusedMem;
  234. //changes screen resolution
  235. function SetScreenResolution(Width, Height: integer): Longint;
  236. {$ENDIF MSWINDOWS}
  237. //returns last day of current month
  238. function LastDayCurrentMonth: TDateTime;
  239. {$IFDEF FPC}
  240. function DateTimeInRange(ADateTime: TDateTime; AStartDateTime, AEndDateTime: TDateTime; aInclusive: Boolean = True): Boolean;
  241. {$ENDIF}
  242. //checks if two datetimes are in same day
  243. function IsSameDay(cBefore, cNow : TDateTime) : Boolean;
  244. //change Time of a DateTime
  245. function ChangeTimeOfADay(aDate : TDateTime; aHour, aMinute, aSecond : Word; aMilliSecond : Word = 0) : TDateTime;
  246. //change Date of a DateTime
  247. function ChangeDateOfADay(aDate : TDateTime; aYear, aMonth, aDay : Word) : TDateTime;
  248. //returns n times a char
  249. function FillStr(const C : Char; const Count : Integer) : string;
  250. //checks if string exists in array of string
  251. function StrInArray(const aValue : string; const aInArray : array of string) : Boolean;
  252. //checks if integer exists in array of integer
  253. function IntInArray(const aValue : Integer; const aInArray : array of Integer) : Boolean;
  254. //check if array is empty
  255. function IsEmptyArray(aArray : TArray<string>) : Boolean; overload;
  256. function IsEmptyArray(aArray : TArray<Integer>) : Boolean; overload;
  257. //returns a number leading zero
  258. function Zeroes(const Number, Len : Int64) : string;
  259. //converts a number to thousand delimeter string
  260. function NumberToStr(const Number : Int64) : string;
  261. //returns n spaces
  262. function Spaces(const Count : Integer) : string;
  263. //returns current date as a string
  264. function NowStr : string;
  265. //returns a new GUID as string
  266. function NewGuidStr : string;
  267. //compare a string with a wildcard pattern (? or *)
  268. function IsLike(cText, Pattern: string) : Boolean;
  269. //Upper case for first letter
  270. function Capitalize(s: string): string;
  271. function CapitalizeWords(s: string): string;
  272. //returns current logged user
  273. function GetLoggedUserName : string;
  274. //returns computer name
  275. function GetComputerName : string;
  276. //Changes incorrect delims in path
  277. function NormalizePathDelim(const cPath : string; const Delim : Char) : string;
  278. //combine paths normalized with delim
  279. function CombinePaths(const aFirstPath, aSecondPath: string; aDelim : Char): string;
  280. //Removes last segment of a path
  281. function RemoveLastPathSegment(cDir : string) : string;
  282. //returns path delimiter if found
  283. function GetPathDelimiter(const aPath : string) : string;
  284. //returns first segment of a path
  285. function GetFirstPathSegment(const aPath : string) : string;
  286. //returns last segment of a path
  287. function GetLastPathSegment(const aPath : string) : string;
  288. //finds swith in commandline params
  289. function ParamFindSwitch(const Switch : string) : Boolean;
  290. //gets value for a switch if exists
  291. function ParamGetSwitch(const Switch : string; var cvalue : string) : Boolean;
  292. //returns app name (filename based)
  293. function GetAppName : string;
  294. //returns app version (major & minor)
  295. function GetAppVersionStr: string;
  296. //returns app version full (major, minor, release & compiled)
  297. function GetAppVersionFullStr: string;
  298. //convert UTC DateTime to Local DateTime
  299. function UTCToLocalTime(GMTTime: TDateTime): TDateTime;
  300. //convert Local DateTime to UTC DateTime
  301. function LocalTimeToUTC(LocalTime : TDateTime): TDateTime;
  302. //convert DateTime to GTM Time string
  303. function DateTimeToGMT(aDate : TDateTime) : string;
  304. //convert GMT Time string to DateTime
  305. function GMTToDateTime(aDate : string) : TDateTime;
  306. //convert DateTime to Json Date format
  307. function DateTimeToJsonDate(aDateTime : TDateTime) : string;
  308. //convert Json Date format to DateTime
  309. function JsonDateToDateTime(const aJsonDate : string) : TDateTime;
  310. //count number of digits of a Integer
  311. function CountDigits(anInt: Cardinal): Cardinal; inline;
  312. //count times a string is present in other string
  313. function CountStr(const aFindStr, aSourceStr : string) : Integer;
  314. //save stream to file
  315. procedure SaveStreamToFile(aStream : TStream; const aFilename : string);
  316. //save stream to string
  317. function StreamToString(aStream : TStream) : string;
  318. function StreamToString2(const aStream: TStream; const aEncoding: TEncoding): string;
  319. //save string to stream
  320. procedure StringToStream(const aStr : string; aStream : TStream);
  321. procedure StringToStream2(const aStr : string; aStream : TStream);
  322. //returns a real comma separated text from stringlist
  323. function CommaText(aList : TStringList) : string; overload;
  324. //returns a real comma separated text from array of string
  325. function CommaText(aArray : TArray<string>) : string; overload;
  326. //returns a string CRLF from array of string
  327. function ArrayToString(aArray : TArray<string>) : string;
  328. //converts TStrings to array
  329. function StringsToArray(aStrings : TStrings) : TArray<string>;
  330. {$IFDEF MSWINDOWS}
  331. //process messages on console applications
  332. procedure ProcessMessages;
  333. //get last error message
  334. function GetLastOSError : String;
  335. {$ENDIF}
  336. {$IF DEFINED(FPC) AND DEFINED(MSWINDOWS)}
  337. function GetLastInputInfo(var plii: TLastInputInfo): BOOL;stdcall; external 'user32' name 'GetLastInputInfo';
  338. {$ENDIF}
  339. function RemoveLastChar(const aText : string) : string;
  340. function DateTimeToSQL(aDateTime : TDateTime) : string;
  341. function IsInteger(const aValue : string) : Boolean;
  342. function IsFloat(const aValue : string) : Boolean;
  343. function IsBoolean(const aValue : string) : Boolean;
  344. //extract a substring and deletes from source string
  345. function ExtractStr(var vSource : string; aIndex : Integer; aCount : Integer) : string;
  346. //get first string between string delimiters
  347. function GetSubString(const aSource, aFirstDelimiter, aLastDelimiter : string) : string;
  348. //get double quoted or dequoted string
  349. function DbQuotedStr(const str : string): string;
  350. function UnDbQuotedStr(const str: string) : string;
  351. //get simple quoted or dequoted string
  352. function SpQuotedStr(const str : string): string;
  353. function UnSpQuotedStr(const str : string): string;
  354. //ternary operator
  355. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : string) : string; overload;
  356. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Integer) : Integer; overload;
  357. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Extended) : Extended; overload;
  358. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : TObject) : TObject; overload;
  359. var
  360. path : TEnvironmentPath;
  361. //Enabled if QuickService is defined
  362. IsQuickServiceApp : Boolean;
  363. implementation
  364. {TFileHelper}
  365. {$IFNDEF FPC}
  366. {$IFDEF MSWINDOWS}
  367. class function TFileHelper.IsInUse(const FileName : string) : Boolean;
  368. var
  369. HFileRes: HFILE;
  370. begin
  371. Result := False;
  372. if not FileExists(FileName) then Exit;
  373. try
  374. HFileRes := CreateFile(PChar(FileName)
  375. ,GENERIC_READ or GENERIC_WRITE
  376. ,0
  377. ,nil
  378. ,OPEN_EXISTING
  379. ,FILE_ATTRIBUTE_NORMAL
  380. ,0);
  381. Result := (HFileRes = INVALID_HANDLE_VALUE);
  382. if not(Result) then begin
  383. CloseHandle(HFileRes);
  384. end;
  385. except
  386. Result := True;
  387. end;
  388. end;
  389. {$ENDIF}
  390. {$IFDEF DELPHILINUX}
  391. class function TFileHelper.IsInUse(const FileName : string) : Boolean;
  392. var
  393. fs : TFileStream;
  394. begin
  395. try
  396. fs := TFileStream.Create(FileName, fmOpenReadWrite, fmShareExclusive);
  397. Result := True;
  398. fs.Free;
  399. except
  400. Result := False;
  401. end;
  402. end;
  403. {$ENDIF}
  404. {$IFDEF MSWINDOWS}
  405. class function TFileHelper.GetSize(const FileName: String): Int64;
  406. var
  407. info: TWin32FileAttributeData;
  408. begin
  409. Result := -1;
  410. if not GetFileAttributesEx(PWideChar(FileName), GetFileExInfoStandard, @info) then Exit;
  411. Result := Int64(info.nFileSizeLow) or Int64(info.nFileSizeHigh shl 32);
  412. end;
  413. {$ELSE}
  414. class function TFileHelper.GetSize(const FileName: String): Int64;
  415. var
  416. sr : TSearchRec;
  417. begin
  418. if FindFirst(fileName, faAnyFile, sr ) = 0 then Result := sr.Size
  419. else Result := -1;
  420. end;
  421. {$ENDIF}
  422. {TDirectoryHelper}
  423. class function TDirectoryHelper.GetSize(const Path: String): Int64;
  424. var
  425. filename : string;
  426. begin
  427. Result := -1;
  428. for filename in TDirectory.GetFiles(Path) do
  429. begin
  430. Result := Result + TFile.GetSize(filename);
  431. end;
  432. end;
  433. {$ENDIF}
  434. {other functions}
  435. function RandomPassword(const PasswordLength : Integer; Complexity : TPasswordComplexity = [pfIncludeNumbers,pfIncludeSigns]) : string;
  436. const
  437. PassAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  438. PassSigns = '@!&$';
  439. PassNumbers = '1234567890';
  440. var
  441. MinNumbers,
  442. MinSigns : Integer;
  443. NumNumbers,
  444. NumSigns : Integer;
  445. begin
  446. Result := '';
  447. Randomize;
  448. //fill all alfa
  449. repeat
  450. Result := Result + PassAlpha[Random(Length(PassAlpha))+1];
  451. until (Length(Result) = PasswordLength);
  452. //checks if need include numbers
  453. if pfIncludeNumbers in Complexity then
  454. begin
  455. MinNumbers := Round(PasswordLength / 10 * 2);
  456. NumNumbers := 0;
  457. if MinNumbers = 0 then MinNumbers := 1;
  458. repeat
  459. Result[Random(PasswordLength)+1] := PassNumbers[Random(Length(PassNumbers))+1];
  460. Inc(NumNumbers);
  461. until NumNumbers = MinNumbers;
  462. end;
  463. //checks if need include signs
  464. if pfIncludeNumbers in Complexity then
  465. begin
  466. MinSigns := Round(PasswordLength / 10 * 1);
  467. NumSigns := 0;
  468. if MinSigns = 0 then MinSigns := 1;
  469. repeat
  470. Result[Random(PasswordLength)+1] := PassSigns[Random(Length(PassSigns))+1];
  471. Inc(NumSigns);
  472. until NumSigns = MinSigns;
  473. end;
  474. end;
  475. function RandomString(const aLength: Integer) : string;
  476. const
  477. chars : string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  478. var
  479. i : Integer;
  480. clong : Integer;
  481. begin
  482. clong := High(chars);
  483. SetLength(Result, aLength);
  484. for i := 1 to aLength do
  485. begin
  486. Result[i] := chars[Random(clong) + 1];
  487. end;
  488. end;
  489. function ExtractFileNameWithoutExt(const FileName: string): string;
  490. begin
  491. Result := TPath.GetFileNameWithoutExtension(FileName);
  492. end;
  493. function UnixToWindowsPath(const UnixPath: string): string;
  494. begin
  495. Result := StringReplace(UnixPath, '/', '\',[rfReplaceAll, rfIgnoreCase]);
  496. end;
  497. function WindowsToUnixPath(const WindowsPath: string): string;
  498. begin
  499. Result := StringReplace(WindowsPath, '\', '/',[rfReplaceAll, rfIgnoreCase]);
  500. end;
  501. function CorrectURLPath(cUrl : string) : string;
  502. var
  503. nurl : string;
  504. begin
  505. nurl := WindowsToUnixPath(cUrl);
  506. nurl := StringReplace(nurl,'//','/',[rfReplaceAll]);
  507. Result := StringReplace(nurl,' ','%20',[rfReplaceAll]);
  508. //TNetEncoding.Url.Encode()
  509. end;
  510. procedure GetEnvironmentPaths;
  511. begin
  512. //gets path
  513. path.EXEPATH := TPath.GetDirectoryName(ParamStr(0));
  514. {$IFDEF MSWINDOWS}
  515. path.WINDOWS := SysUtils.GetEnvironmentVariable('windir');
  516. path.PROGRAMFILES := SysUtils.GetEnvironmentVariable('ProgramFiles');
  517. path.COMMONFILES := SysUtils.GetEnvironmentVariable('CommonProgramFiles(x86)');
  518. path.HOMEDRIVE := SysUtils.GetEnvironmentVariable('SystemDrive');
  519. path.USERPROFILE := SysUtils.GetEnvironmentVariable('USERPROFILE');
  520. path.PROGRAMDATA := SysUtils.GetEnvironmentVariable('ProgramData');
  521. path.ALLUSERSPROFILE := SysUtils.GetEnvironmentVariable('AllUsersProfile');
  522. path.INSTDRIVE := path.HOMEDRIVE;
  523. path.TEMP := SysUtils.GetEnvironmentVariable('TEMP');
  524. //these paths fail if user is SYSTEM
  525. try
  526. path.SYSTEM := GetSpecialFolderPath(CSIDL_SYSTEM);
  527. path.APPDATA := GetSpecialFolderPath(CSIDL_APPDATA);
  528. path.DESKTOP := GetSpecialFolderPath(CSIDL_DESKTOP);
  529. path.DESKTOP_ALLUSERS := GetSpecialFolderPath(CSIDL_COMMON_DESKTOPDIRECTORY);
  530. path.STARTMENU:=GetSpecialFolderPath(CSIDL_PROGRAMS);
  531. path.STARTMENU_ALLUSERS:=GetSpecialFolderPath(CSIDL_COMMON_PROGRAMS);
  532. path.STARTMENU_ALLUSERS := path.STARTMENU;
  533. path.STARTUP:=GetSpecialFolderPath(CSIDL_STARTUP);
  534. except
  535. //
  536. end;
  537. {$ENDIF}
  538. end;
  539. {$IFDEF MSWINDOWS}
  540. function GetSpecialFolderPath(folderID : Integer) : string;
  541. var
  542. ppidl: PItemIdList;
  543. begin
  544. SHGetSpecialFolderLocation(0, folderID, ppidl);
  545. SetLength(Result, MAX_PATH);
  546. if not SHGetPathFromIDList(ppidl,{$IFDEF FPC}PAnsiChar(Result){$ELSE}PChar(Result){$ENDIF}) then
  547. begin
  548. raise EShellError.create(Format('GetSpecialFolderPath: Invalid PIPL (%d)',[folderID]));
  549. end;
  550. SetLength(Result, lStrLen({$IFDEF FPC}PAnsiChar(Result){$ELSE}PChar(Result){$ENDIF}));
  551. end;
  552. function Is64bitOS : Boolean;
  553. begin
  554. {$IFDEF WIN64}
  555. Result := True;
  556. {$ELSE}
  557. Result := False;
  558. {$ENDIF WIN64}
  559. end;
  560. function IsConsole: Boolean;
  561. begin
  562. {$IFDEF CONSOLE}
  563. Result := True;
  564. {$ELSE}
  565. Result := False;
  566. {$ENDIF CONSOLE}
  567. end;
  568. {$ENDIF}
  569. function HasConsoleOutput : Boolean;
  570. {$IFDEF MSWINDOWS}
  571. var
  572. stout : THandle;
  573. begin
  574. try
  575. stout := GetStdHandle(Std_Output_Handle);
  576. Win32Check(stout <> Invalid_Handle_Value);
  577. Result := stout <> 0;
  578. except
  579. Result := False;
  580. end;
  581. end;
  582. {$ELSE}
  583. begin
  584. Result := IsConsole;
  585. end;
  586. {$ENDIF}
  587. function IsDebug: Boolean;
  588. begin
  589. {$IFDEF DEBUG}
  590. Result := True;
  591. {$ELSE}
  592. Result := False;
  593. {$ENDIF DEBUG}
  594. end;
  595. {$IFDEF MSWINDOWS}
  596. function IsService : Boolean;
  597. begin
  598. //only working with my Quick.AppService unit
  599. try
  600. Result := (IsConsole) and (not HasConsoleOutput);
  601. except
  602. Result := False;
  603. end;
  604. end;
  605. function SecondsIdle: DWord;
  606. var
  607. liInfo: TLastInputInfo;
  608. begin
  609. liInfo.cbSize := SizeOf(TLastInputInfo) ;
  610. GetLastInputInfo(liInfo) ;
  611. Result := (GetTickCount - liInfo.dwTime) DIV 1000;
  612. end;
  613. procedure FreeUnusedMem;
  614. begin
  615. if Win32Platform = VER_PLATFORM_WIN32_NT then SetProcessWorkingSetSize(GetCurrentProcess, $FFFFFFFF, $FFFFFFFF);
  616. end;
  617. function SetScreenResolution(Width, Height: integer): Longint;
  618. var
  619. DeviceMode: TDeviceMode;
  620. begin
  621. with DeviceMode do
  622. begin
  623. dmSize := SizeOf(TDeviceMode);
  624. dmPelsWidth := Width;
  625. dmPelsHeight := Height;
  626. dmFields := DM_PELSWIDTH or DM_PELSHEIGHT;
  627. end;
  628. Result := ChangeDisplaySettings(DeviceMode, CDS_UPDATEREGISTRY);
  629. end;
  630. {$ENDIF MSWINDOWS}
  631. function LastDayCurrentMonth: TDateTime;
  632. begin
  633. Result := EncodeDate(YearOf(Now),MonthOf(Now), DaysInMonth(Now));
  634. end;
  635. {$IFDEF FPC}
  636. function DateTimeInRange(ADateTime: TDateTime; AStartDateTime, AEndDateTime: TDateTime; aInclusive: Boolean = True): Boolean;
  637. begin
  638. if aInclusive then
  639. Result := (AStartDateTime <= ADateTime) and (ADateTime <= AEndDateTime)
  640. else
  641. Result := (AStartDateTime < ADateTime) and (ADateTime < AEndDateTime);
  642. end;
  643. {$ENDIF}
  644. function IsSameDay(cBefore, cNow : TDateTime) : Boolean;
  645. begin
  646. //Test: Result := MinutesBetween(cBefore,cNow) < 1;
  647. Result := DateTimeInRange(cNow,StartOfTheDay(cBefore),EndOfTheDay(cBefore),True);
  648. end;
  649. function ChangeTimeOfADay(aDate : TDateTime; aHour, aMinute, aSecond : Word; aMilliSecond : Word = 0) : TDateTime;
  650. var
  651. y, m, d : Word;
  652. begin
  653. DecodeDate(aDate,y,m,d);
  654. Result := EncodeDateTime(y,m,d,aHour,aMinute,aSecond,aMilliSecond);
  655. end;
  656. function ChangeDateOfADay(aDate : TDateTime; aYear, aMonth, aDay : Word) : TDateTime;
  657. var
  658. h, m, s, ms : Word;
  659. begin
  660. DecodeTime(aDate,h,m,s,ms);
  661. Result := EncodeDateTime(aYear,aMonth,aDay,h,m,s,0);
  662. end;
  663. function FillStr(const C : Char; const Count : Integer) : string;
  664. var
  665. i : Integer;
  666. begin
  667. Result := '';
  668. for i := 1 to Count do Result := Result + C;
  669. end;
  670. function StrInArray(const aValue : string; const aInArray : array of string) : Boolean;
  671. var
  672. s : string;
  673. begin
  674. for s in aInArray do
  675. begin
  676. if s = aValue then Exit(True);
  677. end;
  678. Result := False;
  679. end;
  680. function IntInArray(const aValue : Integer; const aInArray : array of Integer) : Boolean;
  681. var
  682. i : Integer;
  683. begin
  684. for i in aInArray do
  685. begin
  686. if i = aValue then Exit(True);
  687. end;
  688. Result := False;
  689. end;
  690. function IsEmptyArray(aArray : TArray<string>) : Boolean;
  691. begin
  692. Result := Length(aArray) = 0;
  693. end;
  694. function IsEmptyArray(aArray : TArray<Integer>) : Boolean;
  695. begin
  696. Result := Length(aArray) = 0;
  697. end;
  698. function Zeroes(const Number, Len : Int64) : string;
  699. begin
  700. if Len > Length(IntToStr(Number)) then Result := FillStr('0',Len - Length(IntToStr(Number))) + IntToStr(Number)
  701. else Result := IntToStr(Number);
  702. end;
  703. function NumberToStr(const Number : Int64) : string;
  704. begin
  705. try
  706. Result := FormatFloat('0,',Number);
  707. except
  708. Result := '#Error';
  709. end;
  710. end;
  711. function Spaces(const Count : Integer) : string;
  712. begin
  713. Result := FillStr(' ',Count);
  714. end;
  715. function NowStr : string;
  716. begin
  717. Result := DateTimeToStr(Now());
  718. end;
  719. function NewGuidStr : string;
  720. {$IFNDEF DELPHIRX10_UP}
  721. var
  722. guid : TGUID;
  723. {$ENDIF}
  724. begin
  725. {$IFDEF DELPHIRX10_UP}
  726. Result := TGUID.NewGuid.ToString;
  727. {$ELSE}
  728. guid.NewGuid;
  729. Result := guid.ToString
  730. {$ENDIF}
  731. end;
  732. function IsLike(cText, Pattern: string) : Boolean;
  733. var
  734. i, n : Integer;
  735. match : Boolean;
  736. wildcard : Boolean;
  737. CurrentPattern : Char;
  738. begin
  739. Result := False;
  740. wildcard := False;
  741. cText := LowerCase(cText);
  742. Pattern := LowerCase(Pattern);
  743. match := False;
  744. if (Pattern.Length > cText.Length) or (Pattern = '') then Exit;
  745. if Pattern = '*' then
  746. begin
  747. Result := True;
  748. Exit;
  749. end;
  750. for i := 1 to cText.Length do
  751. begin
  752. CurrentPattern := Pattern[i];
  753. if CurrentPattern = '*' then wildcard := True;
  754. if wildcard then
  755. begin
  756. n := Pos(Copy(Pattern,i+1,Pattern.Length),cText);
  757. if (n > i) or (Pattern.Length = i) then
  758. begin
  759. Result := True;
  760. Exit;
  761. end;
  762. end
  763. else
  764. begin
  765. if (cText[i] = CurrentPattern) or (CurrentPattern = '?') then match := True
  766. else match := False;
  767. end;
  768. end;
  769. Result := match;
  770. end;
  771. function Capitalize(s: string): string;
  772. begin
  773. Result := '';
  774. if s.Length = 0 then Exit;
  775. s := LowerCase(s,loUserLocale);
  776. Result := UpperCase(s[1],loUserLocale) + Trim(Copy(s, 2, s.Length));
  777. end;
  778. function CapitalizeWords(s: string): string;
  779. var
  780. cword : string;
  781. begin
  782. Result := '';
  783. if s.Length = 0 then Exit;
  784. s := LowerCase(s,loUserLocale);
  785. for cword in s.Split([' ']) do
  786. begin
  787. if Result = '' then Result := Capitalize(cword)
  788. else Result := Result + ' ' + Capitalize(cword);
  789. end;
  790. end;
  791. function GetLoggedUserName : string;
  792. {$IFDEF MSWINDOWS}
  793. const
  794. cnMaxUserNameLen = 254;
  795. var
  796. sUserName : string;
  797. dwUserNameLen : DWord;
  798. begin
  799. dwUserNameLen := cnMaxUserNameLen-1;
  800. SetLength( sUserName, cnMaxUserNameLen );
  801. GetUserName(PChar( sUserName ),dwUserNameLen );
  802. SetLength( sUserName, dwUserNameLen );
  803. Result := sUserName;
  804. end;
  805. {$ELSE}
  806. {$IF DEFINED(FPC) AND DEFINED(LINUX)}
  807. begin
  808. Result := GetEnvironmentVariable('USERNAME');
  809. end;
  810. {$ELSE}
  811. var
  812. {$IFNDEF NEXTGEN}
  813. plogin : PAnsiChar;
  814. {$ELSE}
  815. plogin : MarshaledAString;
  816. {$ENDIF}
  817. begin
  818. {$IFDEF POSIX}
  819. try
  820. plogin := getlogin;
  821. Result := Copy(plogin,1,Length(Trim(plogin)));
  822. except
  823. Result := 'N/A';
  824. end;
  825. {$ELSE}
  826. Result := 'N/A';
  827. {$ENDIF}
  828. //raise ENotImplemented.Create('Not Android GetLoggedUserName implemented!');
  829. end;
  830. {$ENDIF}
  831. {$ENDIF}
  832. {$IFDEF IOS}
  833. function GetDeviceModel : String;
  834. var
  835. size : size_t;
  836. buffer : array of Byte;
  837. begin
  838. sysctlbyname('hw.machine',nil,@size,nil,0);
  839. if size > 0 then
  840. begin
  841. SetLength(buffer, size);
  842. sysctlbyname('hw.machine',@buffer[0],@size,nil,0);
  843. Result := UTF8ToString(MarshaledAString(buffer));
  844. end
  845. else Result := EmptyStr;
  846. end;
  847. {$ENDIF}
  848. function GetComputerName : string;
  849. {$IFDEF MSWINDOWS}
  850. var
  851. dwLength: dword;
  852. begin
  853. dwLength := 253;
  854. SetLength(Result, dwLength+1);
  855. if not Windows.GetComputerName(pchar(result), dwLength) then Result := 'Not detected!';
  856. Result := pchar(result);
  857. end;
  858. {$ELSE}
  859. {$IF DEFINED(FPC) AND DEFINED(LINUX)}
  860. begin
  861. Result := GetEnvironmentVariable('COMPUTERNAME');
  862. end;
  863. {$ELSE} //Android gets model name
  864. {$IFDEF NEXTGEN}
  865. begin
  866. {$IFDEF ANDROID}
  867. Result := JStringToString(TJBuild.JavaClass.MODEL);
  868. {$ELSE} //IOS
  869. Result := GetDeviceModel;
  870. {$ENDIF}
  871. end;
  872. {$ELSE}
  873. {$IFDEF DELPHILINUX}
  874. var
  875. phost : PAnsiChar;
  876. begin
  877. try
  878. phost := AllocMem(256);
  879. try
  880. if gethostname(phost,_SC_HOST_NAME_MAX) = 0 then
  881. begin
  882. {$IFDEF DEBUG}
  883. Result := Copy(Trim(phost),1,Length(Trim(phost)));
  884. {$ELSE}
  885. Result := Copy(phost,1,Length(phost));
  886. {$ENDIF}
  887. end
  888. else Result := 'N/A.';
  889. finally
  890. FreeMem(phost);
  891. end;
  892. except
  893. Result := 'N/A';
  894. end;
  895. end;
  896. {$ELSE} //OSX
  897. begin
  898. Result := NSStrToStr(TNSHost.Wrap(TNSHost.OCClass.currentHost).localizedName);
  899. end;
  900. {$ENDIF}
  901. {$ENDIF}
  902. {$ENDIF}
  903. {$ENDIF}
  904. function NormalizePathDelim(const cPath : string; const Delim : Char) : string;
  905. begin
  906. if Delim = '\' then Result := StringReplace(cPath,'/',Delim,[rfReplaceAll])
  907. else Result := StringReplace(cPath,'\',Delim,[rfReplaceAll]);
  908. end;
  909. function CombinePaths(const aFirstPath, aSecondPath: string; aDelim : Char): string;
  910. begin
  911. var path1 := NormalizePathDelim(aFirstPath,aDelim);
  912. var path2 := NormalizePathDelim(aSecondPath,aDelim);
  913. if path1.EndsWith(aDelim) then
  914. begin
  915. if path2.StartsWith(aDelim) then Result := path1 + path2.Substring(1)
  916. else Result := path1 + path2;
  917. end
  918. else
  919. begin
  920. if path2.StartsWith(aDelim) then Result := path1 + path2
  921. else result := path1 + aDelim + path2;
  922. end;
  923. end;
  924. function RemoveLastPathSegment(cDir : string) : string;
  925. var
  926. posi : Integer;
  927. delim : Char;
  928. EndsWithDelim : Boolean;
  929. begin
  930. if cDir.Contains('\') then delim := '\'
  931. else if cDir.Contains('/') then delim := '/'
  932. else
  933. begin
  934. Result := '';
  935. Exit;
  936. end;
  937. NormalizePathDelim(cDir,delim);
  938. if cDir.EndsWith(delim) then
  939. begin
  940. cDir := Copy(cDir,1,cDir.Length-1);
  941. EndsWithDelim := True;
  942. end
  943. else EndsWithDelim := False;
  944. if cDir.CountChar(delim) > 1 then posi := cDir.LastDelimiter(delim)
  945. else posi := Pos(delim,cDir)-1;
  946. if posi = cDir.Length then posi := 0;
  947. Result := Copy(cDir,1,posi);
  948. if (Result <> '') and (EndsWithDelim) then Result := Result + delim;
  949. end;
  950. function GetPathDelimiter(const aPath : string) : string;
  951. begin
  952. if aPath.Contains('/') then Result := '/'
  953. else if aPath.Contains('\') then Result := '\'
  954. else Result := '';
  955. end;
  956. function GetFirstPathSegment(const aPath : string) : string;
  957. var
  958. delimiter : string;
  959. spath : string;
  960. begin
  961. delimiter := GetPathDelimiter(aPath);
  962. if delimiter.IsEmpty then Exit(aPath);
  963. if aPath.StartsWith(delimiter) then spath := Copy(aPath,2,aPath.Length)
  964. else spath := aPath;
  965. Result := Copy(spath,0,spath.IndexOf(delimiter));
  966. end;
  967. function GetLastPathSegment(const aPath : string) : string;
  968. var
  969. delimiter : string;
  970. spath : string;
  971. begin
  972. delimiter := GetPathDelimiter(aPath);
  973. if delimiter.IsEmpty then Exit(aPath);
  974. if aPath.EndsWith(delimiter) then spath := Copy(aPath,0,aPath.Length - 1)
  975. else spath := aPath;
  976. Result := spath.Substring(spath.LastDelimiter(delimiter)+1);
  977. end;
  978. function ParamFindSwitch(const Switch : string) : Boolean;
  979. begin
  980. Result := FindCmdLineSwitch(Switch,['-', '/'],True);
  981. end;
  982. {$IFDEF FPC}
  983. function FindCmdLineSwitch(const Switch: string; var Value: string; IgnoreCase: Boolean = True;
  984. const SwitchTypes: TCmdLineSwitchTypes = [clstValueNextParam, clstValueAppended]): Boolean; overload;
  985. type
  986. TCompareProc = function(const S1, S2: string): Boolean;
  987. var
  988. Param: string;
  989. I, ValueOfs,
  990. SwitchLen, ParamLen: Integer;
  991. SameSwitch: TCompareProc;
  992. begin
  993. Result := False;
  994. Value := '';
  995. if IgnoreCase then
  996. SameSwitch := SameText else
  997. SameSwitch := SameStr;
  998. SwitchLen := Switch.Length;
  999. for I := 1 to ParamCount do
  1000. begin
  1001. Param := ParamStr(I);
  1002. if CharInSet(Param.Chars[0], SwitchChars) and SameSwitch(Param.SubString(1,SwitchLen), Switch) then
  1003. begin
  1004. ParamLen := Param.Length;
  1005. // Look for an appended value if the param is longer than the switch
  1006. if (ParamLen > SwitchLen + 1) then
  1007. begin
  1008. // If not looking for appended value switches then this is not a matching switch
  1009. if not (clstValueAppended in SwitchTypes) then
  1010. Continue;
  1011. ValueOfs := SwitchLen + 1;
  1012. if Param.Chars[ValueOfs] = ':' then
  1013. Inc(ValueOfs);
  1014. Value := Param.SubString(ValueOfs, MaxInt);
  1015. end
  1016. // If the next param is not a switch, then treat it as the value
  1017. else if (clstValueNextParam in SwitchTypes) and (I < ParamCount) and
  1018. not CharInSet(ParamStr(I+1).Chars[0], SwitchChars) then
  1019. Value := ParamStr(I+1);
  1020. Result := True;
  1021. Break;
  1022. end;
  1023. end;
  1024. end;
  1025. {$ENDIF}
  1026. function ParamGetSwitch(const Switch : string; var cvalue : string) : Boolean;
  1027. begin
  1028. Result := FindCmdLineSwitch(Switch,cvalue,True,[clstValueAppended]);
  1029. end;
  1030. function GetAppName : string;
  1031. begin
  1032. Result := ExtractFilenameWithoutExt(ParamStr(0));
  1033. end;
  1034. function GetAppVersionStr: string;
  1035. {$IFDEF MSWINDOWS}
  1036. var
  1037. Rec: LongRec;
  1038. ver : Cardinal;
  1039. begin
  1040. ver := GetFileVersion(ParamStr(0));
  1041. if ver <> Cardinal(-1) then
  1042. begin
  1043. Rec := LongRec(ver);
  1044. Result := Format('%d.%d', [Rec.Hi, Rec.Lo]);
  1045. end
  1046. else Result := '';
  1047. end;
  1048. {$ELSE}
  1049. {$IF DEFINED(FPC) AND DEFINED(LINUX)}
  1050. var
  1051. version : TProgramVersion;
  1052. begin
  1053. if GetProgramVersion(version) then Result := Format('%d.%d', [version.Major, version.Minor])
  1054. else Result := '';
  1055. end;
  1056. {$ELSE}
  1057. {$IFDEF NEXTGEN}
  1058. {$IFDEF ANDROID}
  1059. var
  1060. PkgInfo : JPackageInfo;
  1061. begin
  1062. PkgInfo := SharedActivity.getPackageManager.getPackageInfo(SharedActivity.getPackageName,0);
  1063. Result := IntToStr(PkgInfo.VersionCode);
  1064. end;
  1065. {$ELSE} //IOS
  1066. var
  1067. AppKey: Pointer;
  1068. AppBundle: NSBundle;
  1069. BuildStr : NSString;
  1070. begin
  1071. try
  1072. AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID;
  1073. AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
  1074. BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey));
  1075. Result := UTF8ToString(BuildStr.UTF8String);
  1076. except
  1077. Result := '';
  1078. end;
  1079. end;
  1080. {$ENDIF}
  1081. {$ELSE} //OSX
  1082. {$IFDEF OSX}
  1083. var
  1084. AppKey: Pointer;
  1085. AppBundle: NSBundle;
  1086. BuildStr : NSString;
  1087. begin
  1088. try
  1089. AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID;
  1090. AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
  1091. BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey));
  1092. Result := UTF8ToString(BuildStr.UTF8String);
  1093. except
  1094. Result := '';
  1095. end;
  1096. end;
  1097. {$ELSE}
  1098. begin
  1099. Result := '';
  1100. end;
  1101. {$ENDIF}
  1102. {$ENDIF}
  1103. {$ENDIF}
  1104. {$ENDIF}
  1105. function GetAppVersionFullStr: string;
  1106. {$IFDEF MSWINDOWS}
  1107. var
  1108. Exe: string;
  1109. Size, Handle: DWORD;
  1110. Buffer: TBytes;
  1111. FixedPtr: PVSFixedFileInfo;
  1112. begin
  1113. Result := '';
  1114. Exe := ParamStr(0);
  1115. Size := GetFileVersionInfoSize(PChar(Exe), Handle);
  1116. if Size = 0 then
  1117. begin
  1118. //RaiseLastOSError;
  1119. //no version info in file
  1120. Exit;
  1121. end;
  1122. SetLength(Buffer, Size);
  1123. if not GetFileVersionInfo(PChar(Exe), Handle, Size, Buffer) then
  1124. RaiseLastOSError;
  1125. if not VerQueryValue(Buffer, '\', Pointer(FixedPtr), Size) then
  1126. RaiseLastOSError;
  1127. if (LongRec(FixedPtr.dwFileVersionLS).Hi = 0) and (LongRec(FixedPtr.dwFileVersionLS).Lo = 0) then
  1128. begin
  1129. Result := Format('%d.%d',
  1130. [LongRec(FixedPtr.dwFileVersionMS).Hi, //major
  1131. LongRec(FixedPtr.dwFileVersionMS).Lo]); //minor
  1132. end
  1133. else if (LongRec(FixedPtr.dwFileVersionLS).Lo = 0) then
  1134. begin
  1135. Result := Format('%d.%d.%d',
  1136. [LongRec(FixedPtr.dwFileVersionMS).Hi, //major
  1137. LongRec(FixedPtr.dwFileVersionMS).Lo, //minor
  1138. LongRec(FixedPtr.dwFileVersionLS).Hi]); //release
  1139. end
  1140. else
  1141. begin
  1142. Result := Format('%d.%d.%d.%d',
  1143. [LongRec(FixedPtr.dwFileVersionMS).Hi, //major
  1144. LongRec(FixedPtr.dwFileVersionMS).Lo, //minor
  1145. LongRec(FixedPtr.dwFileVersionLS).Hi, //release
  1146. LongRec(FixedPtr.dwFileVersionLS).Lo]); //build
  1147. end;
  1148. end;
  1149. {$ELSE}
  1150. {$IF DEFINED(FPC) AND DEFINED(LINUX)}
  1151. var
  1152. version : TProgramVersion;
  1153. begin
  1154. if GetProgramVersion(version) then Result := Format('%d.%d.%d.%d', [version.Major, version.Minor, version.Revision, version.Build])
  1155. else Result := '';
  1156. end;
  1157. {$ELSE}
  1158. {$IFDEF NEXTGEN}
  1159. {$IFDEF ANDROID}
  1160. var
  1161. PkgInfo : JPackageInfo;
  1162. begin
  1163. PkgInfo := SharedActivity.getPackageManager.getPackageInfo(SharedActivity.getPackageName,0);
  1164. Result := JStringToString(PkgInfo.versionName);
  1165. end;
  1166. {$ELSE} //IOS
  1167. var
  1168. AppKey: Pointer;
  1169. AppBundle: NSBundle;
  1170. BuildStr : NSString;
  1171. begin
  1172. AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID;
  1173. AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
  1174. BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey));
  1175. Result := UTF8ToString(BuildStr.UTF8String);
  1176. end;
  1177. {$ENDIF}
  1178. {$ELSE}
  1179. {$IFDEF OSX}
  1180. var
  1181. AppKey: Pointer;
  1182. AppBundle: NSBundle;
  1183. BuildStr : NSString;
  1184. begin
  1185. AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID;
  1186. AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
  1187. BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey));
  1188. Result := UTF8ToString(BuildStr.UTF8String);
  1189. end;
  1190. {$ELSE}
  1191. begin
  1192. Result := '';
  1193. end;
  1194. {$ENDIF}
  1195. {$ENDIF}
  1196. {$ENDIF}
  1197. {$ENDIF}
  1198. function UTCToLocalTime(GMTTime: TDateTime): TDateTime;
  1199. begin
  1200. {$IFDEF FPC}
  1201. Result := LocalTimeToUniversal(GMTTime);
  1202. {$ELSE}
  1203. Result := TTimeZone.Local.ToLocalTime(GMTTime);
  1204. {$ENDIF}
  1205. end;
  1206. function LocalTimeToUTC(LocalTime : TDateTime): TDateTime;
  1207. begin
  1208. {$IFDEF FPC}
  1209. Result := UniversalTimeToLocal(Localtime);
  1210. {$ELSE}
  1211. Result := TTimeZone.Local.ToUniversalTime(LocalTime);
  1212. {$ENDIF}
  1213. end;
  1214. function DateTimeToGMT(aDate : TDateTime) : string;
  1215. var
  1216. FmtSettings : TFormatSettings;
  1217. begin
  1218. FmtSettings.DateSeparator := '-';
  1219. FmtSettings.TimeSeparator := ':';
  1220. FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ" GMT"';
  1221. Result := DateTimeToStr(aDate,FmtSettings).Trim;
  1222. end;
  1223. function GMTToDateTime(aDate : string) : TDateTime;
  1224. var
  1225. FmtSettings : TFormatSettings;
  1226. begin
  1227. FmtSettings.DateSeparator := '-';
  1228. FmtSettings.TimeSeparator := ':';
  1229. FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ" GMT"';
  1230. Result := StrToDateTime(aDate,FmtSettings);
  1231. end;
  1232. function DateTimeToJsonDate(aDateTime : TDateTime) : string;
  1233. {$IFNDEF DELPHIXE7_UP}
  1234. var
  1235. FmtSettings : TFormatSettings;
  1236. {$ENDIF}
  1237. begin
  1238. {$IFDEF DELPHIXE7_UP}
  1239. Result := DateToISO8601(aDateTime);
  1240. {$ELSE}
  1241. FmtSettings.DateSeparator := '-';
  1242. FmtSettings.TimeSeparator := ':';
  1243. FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ"Z"';
  1244. Result := DateTimeToStr(aDateTime,FmtSettings).Trim;
  1245. {$ENDIF}
  1246. end;
  1247. function JsonDateToDateTime(const aJsonDate : string) : TDateTime;
  1248. {$IFNDEF DELPHIXE7_UP}
  1249. var
  1250. FmtSettings : TFormatSettings;
  1251. {$ENDIF}
  1252. {$IFDEF FPC}
  1253. var
  1254. jdate : string;
  1255. {$ENDIF}
  1256. begin
  1257. {$IFDEF DELPHIXE7_UP}
  1258. Result := ISO8601ToDate(aJsonDate);
  1259. {$ELSE}
  1260. FmtSettings.DateSeparator := '-';
  1261. FmtSettings.TimeSeparator := ':';
  1262. FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ"Z"';
  1263. {$IFDEF FPC}
  1264. jdate := StringReplace(aJsondate,'T',' ',[rfIgnoreCase]);
  1265. jdate := Copy(jdate,1,Pos('.',jdate)-1);
  1266. Result := StrToDateTime(jdate,FmtSettings);
  1267. {$ELSE}
  1268. Result := StrToDateTime(aJsonDate,FmtSettings);
  1269. {$ENDIF}
  1270. {$ENDIF}
  1271. end;
  1272. function CountDigits(anInt: Cardinal): Cardinal; inline;
  1273. var
  1274. cmp: Cardinal;
  1275. begin
  1276. cmp := 10;
  1277. Result := 1;
  1278. while (Result < 10) and (cmp <= anInt) do
  1279. begin
  1280. cmp := cmp*10;
  1281. Inc(Result);
  1282. end;
  1283. end;
  1284. function CountStr(const aFindStr, aSourceStr : string) : Integer;
  1285. var
  1286. i : Integer;
  1287. found : Integer;
  1288. findstr : string;
  1289. mainstr : string;
  1290. begin
  1291. findstr := aFindStr.ToLower;
  1292. mainstr := aSourceStr.ToLower;
  1293. Result := 0;
  1294. i := 0;
  1295. while i < mainstr.Length do
  1296. begin
  1297. found := Pos(findstr,mainstr,i);
  1298. if found > 0 then
  1299. begin
  1300. i := found;
  1301. Inc(Result);
  1302. end
  1303. else Break;
  1304. end;
  1305. end;
  1306. procedure SaveStreamToFile(aStream : TStream; const aFileName : string);
  1307. var
  1308. fs : TFileStream;
  1309. begin
  1310. fs := TFileStream.Create(aFileName,fmCreate);
  1311. try
  1312. aStream.Seek(0,soBeginning);
  1313. fs.CopyFrom(aStream,aStream.Size);
  1314. finally
  1315. fs.Free;
  1316. end;
  1317. end;
  1318. function StreamToString(aStream : TStream) : string;
  1319. var
  1320. ss : TStringStream;
  1321. begin
  1322. aStream.Position := 0;
  1323. if aStream = nil then Exit;
  1324. if aStream is TMemoryStream then
  1325. begin
  1326. SetString(Result, PChar(TMemoryStream(aStream).Memory), TMemoryStream(aStream).Size div SizeOf(Char));
  1327. end
  1328. else if aStream is TStringStream then
  1329. begin
  1330. Result := TStringStream(aStream).DataString;
  1331. end
  1332. else
  1333. begin
  1334. ss := TStringStream.Create;
  1335. try
  1336. aStream.Seek(0,soBeginning);
  1337. ss.CopyFrom(aStream,aStream.Size);
  1338. Result := ss.DataString;
  1339. finally
  1340. ss.Free;
  1341. end;
  1342. end;
  1343. end;
  1344. function StreamToString2(const aStream: TStream; const aEncoding: TEncoding): string;
  1345. var
  1346. sbytes: TBytes;
  1347. begin
  1348. aStream.Position := 0;
  1349. SetLength(sbytes, aStream.Size);
  1350. aStream.ReadBuffer(sbytes,aStream.Size);
  1351. Result := aEncoding.GetString(sbytes);
  1352. end;
  1353. procedure StringToStream(const aStr : string; aStream : TStream);
  1354. begin
  1355. aStream.Seek(0,soBeginning);
  1356. aStream.WriteBuffer(Pointer(aStr)^,aStr.Length * SizeOf(Char));
  1357. end;
  1358. procedure StringToStream2(const aStr : string; aStream : TStream);
  1359. var
  1360. stream : TStringStream;
  1361. begin
  1362. stream := TStringStream.Create(aStr,TEncoding.UTF8);
  1363. try
  1364. aStream.CopyFrom(stream,stream.Size);
  1365. finally
  1366. stream.Free;
  1367. end;
  1368. end;
  1369. function CommaText(aList : TStringList) : string;
  1370. var
  1371. value : string;
  1372. sb : TStringBuilder;
  1373. begin
  1374. if aList.Text = '' then Exit;
  1375. sb := TStringBuilder.Create;
  1376. try
  1377. for value in aList do
  1378. begin
  1379. sb.Append(value);
  1380. sb.Append(',');
  1381. end;
  1382. if sb.Length > 1 then Result := sb.ToString(0, sb.Length - 1);
  1383. finally
  1384. sb.Free;
  1385. end;
  1386. end;
  1387. function CommaText(aArray : TArray<string>) : string;
  1388. var
  1389. value : string;
  1390. sb : TStringBuilder;
  1391. begin
  1392. if High(aArray) < 0 then Exit;
  1393. sb := TStringBuilder.Create;
  1394. try
  1395. for value in aArray do
  1396. begin
  1397. sb.Append(value);
  1398. sb.Append(',');
  1399. end;
  1400. if sb.Length > 1 then Result := sb.ToString(0, sb.Length - 1);
  1401. finally
  1402. sb.Free;
  1403. end;
  1404. end;
  1405. function ArrayToString(aArray : TArray<string>) : string;
  1406. var
  1407. value : string;
  1408. sb : TStringBuilder;
  1409. begin
  1410. if High(aArray) < 0 then Exit;
  1411. sb := TStringBuilder.Create;
  1412. try
  1413. for value in aArray do
  1414. begin
  1415. sb.Append(value);
  1416. sb.Append(#10#13);
  1417. end;
  1418. finally
  1419. sb.Free;
  1420. end;
  1421. end;
  1422. function StringsToArray(aStrings : TStrings) : TArray<string>;
  1423. var
  1424. i : Integer;
  1425. begin
  1426. if aStrings.Count = 0 then Exit;
  1427. SetLength(Result,aStrings.Count);
  1428. for i := 0 to aStrings.Count - 1 do
  1429. begin
  1430. Result[i] := aStrings[i];
  1431. end;
  1432. end;
  1433. { TCounter }
  1434. procedure TCounter.Init(aMaxValue : Integer);
  1435. begin
  1436. fMaxValue := aMaxValue;
  1437. fCurrentValue := 0;
  1438. end;
  1439. function TCounter.Count : Integer;
  1440. begin
  1441. Result := fCurrentValue;
  1442. end;
  1443. function TCounter.CountIs(aValue : Integer) : Boolean;
  1444. begin
  1445. Result := fCurrentValue = aValue;
  1446. end;
  1447. function TCounter.Check : Boolean;
  1448. begin
  1449. if fCurrentValue = fMaxValue then
  1450. begin
  1451. Result := True;
  1452. Reset;
  1453. end
  1454. else
  1455. begin
  1456. Result := False;
  1457. Inc(fCurrentValue);
  1458. end;
  1459. end;
  1460. procedure TCounter.Reset;
  1461. begin
  1462. fCurrentValue := fMaxValue;
  1463. end;
  1464. { TimeCounter }
  1465. procedure TTimeCounter.Init(MillisecondsToReach : Integer);
  1466. begin
  1467. fDoneEvery := MillisecondsToReach;
  1468. end;
  1469. function TTimeCounter.Check : Boolean;
  1470. begin
  1471. if MilliSecondsBetween(fCurrentTime,Now) > fDoneEvery then
  1472. begin
  1473. fCurrentTime := Now();
  1474. Result := True;
  1475. end
  1476. else Result := False;
  1477. end;
  1478. procedure TTimeCounter.Reset;
  1479. begin
  1480. fCurrentTime := Now();
  1481. end;
  1482. { TArrayOfStringHelper}
  1483. {$IFNDEF FPC}
  1484. function TArrayOfStringHelper.Any : Boolean;
  1485. begin
  1486. Result := High(Self) >= 0;
  1487. end;
  1488. function TArrayOfStringHelper.Any(const aValue : string) : Boolean;
  1489. begin
  1490. Result := Exists(aValue);
  1491. end;
  1492. function TArrayOfStringHelper.Add(const aValue : string) : Integer;
  1493. begin
  1494. SetLength(Self,Length(Self)+1);
  1495. Self[High(Self)] := aValue;
  1496. Result := High(Self);
  1497. end;
  1498. function TArrayOfStringHelper.AddIfNotExists(const aValue : string; aCaseSense : Boolean = False) : Integer;
  1499. var
  1500. i : Integer;
  1501. begin
  1502. for i := Low(Self) to High(Self) do
  1503. begin
  1504. if aCaseSense then
  1505. begin
  1506. if Self[i] = aValue then Exit(i);
  1507. end
  1508. else
  1509. begin
  1510. if CompareText(Self[i],aValue) = 0 then Exit(i)
  1511. end;
  1512. end;
  1513. //if not exists add it
  1514. Result := Self.Add(aValue);
  1515. end;
  1516. function TArrayOfStringHelper.Remove(const aValue : string) : Boolean;
  1517. var
  1518. i : Integer;
  1519. begin
  1520. for i := Low(Self) to High(Self) do
  1521. begin
  1522. if CompareText(Self[i],aValue) = 0 then
  1523. begin
  1524. {$IFDEF DELPHIXE7_UP}
  1525. System.Delete(Self,i,1);
  1526. {$ELSE}
  1527. TArrayUtil<string>.Delete(Self,i);
  1528. {$ENDIF}
  1529. Exit(True);
  1530. end;
  1531. end;
  1532. Result := False;
  1533. end;
  1534. function TArrayOfStringHelper.Exists(const aValue : string) : Boolean;
  1535. var
  1536. value : string;
  1537. begin
  1538. Result := False;
  1539. for value in Self do
  1540. begin
  1541. if CompareText(value,aValue) = 0 then Exit(True)
  1542. end;
  1543. end;
  1544. function TArrayOfStringHelper.Count : Integer;
  1545. begin
  1546. Result := High(Self) + 1;
  1547. end;
  1548. {$ENDIF}
  1549. { TPairItem }
  1550. constructor TPairItem.Create(const aName, aValue: string);
  1551. begin
  1552. Name := aName;
  1553. Value := aValue;
  1554. end;
  1555. { TPairList }
  1556. function TPairList.GetEnumerator : TPairEnumerator;
  1557. begin
  1558. Result := TPairEnumerator.Create(fItems);
  1559. end;
  1560. function TPairList.Add(aPair: TPairItem): Integer;
  1561. begin
  1562. SetLength(fItems,Length(fItems)+1);
  1563. fItems[High(fItems)] := aPair;
  1564. Result := High(fItems);
  1565. end;
  1566. function TPairList.Add(const aName, aValue: string): Integer;
  1567. begin
  1568. SetLength(fItems,Length(fItems)+1);
  1569. fItems[High(fItems)].Name := aName;
  1570. fItems[High(fItems)].Value := aValue;
  1571. Result := High(fItems);
  1572. end;
  1573. procedure TPairList.AddOrUpdate(const aName, aValue: string);
  1574. var
  1575. i : Integer;
  1576. begin
  1577. for i := Low(fItems) to High(fItems) do
  1578. begin
  1579. if CompareText(fItems[i].Name,aName) = 0 then
  1580. begin
  1581. fItems[i].Value := aValue;
  1582. Exit;
  1583. end;
  1584. end;
  1585. //if not exists add it
  1586. Self.Add(aName,aValue);
  1587. end;
  1588. function TPairList.Count: Integer;
  1589. begin
  1590. Result := High(fItems) + 1;
  1591. end;
  1592. function TPairList.Exists(const aName: string): Boolean;
  1593. var
  1594. i : Integer;
  1595. begin
  1596. Result := False;
  1597. for i := Low(fItems) to High(fItems) do
  1598. begin
  1599. if CompareText(fItems[i].Name,aName) = 0 then Exit(True)
  1600. end;
  1601. end;
  1602. function TPairList.GetPair(const aName: string): TPairItem;
  1603. var
  1604. i : Integer;
  1605. begin
  1606. for i := Low(fItems) to High(fItems) do
  1607. begin
  1608. if CompareText(fItems[i].Name,aName) = 0 then Exit(fItems[i]);
  1609. end;
  1610. end;
  1611. function TPairList.GetValue(const aName: string): string;
  1612. var
  1613. i : Integer;
  1614. begin
  1615. Result := '';
  1616. for i := Low(fItems) to High(fItems) do
  1617. begin
  1618. if CompareText(fItems[i].Name,aName) = 0 then Exit(fItems[i].Value);
  1619. end;
  1620. end;
  1621. function TPairList.Remove(const aName: string): Boolean;
  1622. var
  1623. i : Integer;
  1624. begin
  1625. for i := Low(fItems) to High(fItems) do
  1626. begin
  1627. if CompareText(fItems[i].Name,aName) = 0 then
  1628. begin
  1629. {$IF Defined(DELPHIXE7_UP) OR Defined(FPC)}
  1630. System.Delete(fItems,i,1);
  1631. {$ELSE}
  1632. TArrayUtil<TPairItem>.Delete(fItems,i);
  1633. {$ENDIF}
  1634. Exit(True);
  1635. end;
  1636. end;
  1637. Result := False;
  1638. end;
  1639. function TPairList.ToArray : TArray<TPairItem>;
  1640. begin
  1641. Result := fItems;
  1642. end;
  1643. procedure TPairList.FromArray(aValue : TArray<TPairItem>);
  1644. begin
  1645. fItems := aValue;
  1646. end;
  1647. procedure TPairList.Clear;
  1648. begin
  1649. SetLength(fItems,0);
  1650. end;
  1651. { TPairList.TPairEnumerator}
  1652. constructor TPairList.TPairEnumerator.Create(var aArray: TArray<TPairItem>);
  1653. begin
  1654. fIndex := -1;
  1655. fArray := @aArray;
  1656. end;
  1657. function TPairList.TPairEnumerator.GetCurrent : TPairItem;
  1658. begin
  1659. Result := TArray<TPairItem>(fArray^)[fIndex];
  1660. end;
  1661. function TPairList.TPairEnumerator.MoveNext: Boolean;
  1662. begin
  1663. Inc(fIndex);
  1664. Result := fIndex < High(TArray<TPairItem>(fArray^))+1;
  1665. end;
  1666. {$IFDEF MSWINDOWS}
  1667. procedure ProcessMessages;
  1668. var
  1669. Msg: TMsg;
  1670. begin
  1671. while integer(PeekMessage(Msg, 0, 0, 0, PM_REMOVE)) <> 0 do
  1672. begin
  1673. TranslateMessage(Msg);
  1674. DispatchMessage(Msg);
  1675. end;
  1676. end;
  1677. function GetLastOSError: String;
  1678. begin
  1679. Result := SysErrorMessage(Windows.GetLastError);
  1680. end;
  1681. {$ENDIF}
  1682. function RemoveLastChar(const aText : string) : string;
  1683. begin
  1684. Result := aText.Remove(aText.Length - 1);
  1685. end;
  1686. function DateTimeToSQL(aDateTime : TDateTime) : string;
  1687. begin
  1688. Result := FormatDateTime('YYYYMMDD hh:mm:ss',aDateTime);
  1689. end;
  1690. function IsInteger(const aValue : string) : Boolean;
  1691. var
  1692. i : Integer;
  1693. begin
  1694. Result := TryStrToInt(aValue,i);
  1695. end;
  1696. function IsFloat(const aValue : string) : Boolean;
  1697. var
  1698. e : Extended;
  1699. begin
  1700. Result := TryStrToFloat(aValue,e);
  1701. end;
  1702. function IsBoolean(const aValue : string) : Boolean;
  1703. var
  1704. b : Boolean;
  1705. begin
  1706. Result := TryStrToBool(aValue,b);
  1707. end;
  1708. function ExtractStr(var vSource : string; aIndex : Integer; aCount : Integer) : string;
  1709. begin
  1710. if aIndex > vSource.Length then Exit('');
  1711. Result := Copy(vSource,aIndex,aCount);
  1712. Delete(vSource,aIndex,aCount);
  1713. end;
  1714. function GetSubString(const aSource, aFirstDelimiter, aLastDelimiter : string) : string;
  1715. var
  1716. i : Integer;
  1717. begin
  1718. i := Pos(aFirstDelimiter,aSource);
  1719. if i > -1 then Result := Copy(aSource, i + aFirstDelimiter.Length, Pos(aLastDelimiter, aSource, i + aFirstDelimiter.Length) - i - aFirstDelimiter.Length)
  1720. else Result := '';
  1721. end;
  1722. function DbQuotedStr(const str : string): string;
  1723. var
  1724. i : Integer;
  1725. begin
  1726. Result := str;
  1727. for i := Result.Length - 1 downto 0 do
  1728. begin
  1729. if Result.Chars[i] = '"' then Result := Result.Insert(i, '"');
  1730. end;
  1731. Result := '"' + Result + '"';
  1732. end;
  1733. function UnDbQuotedStr(const str: string) : string;
  1734. begin
  1735. Result := Trim(str);
  1736. if not Result.IsEmpty then
  1737. begin
  1738. if Result.StartsWith('"') then Result := Copy(Result, 2, Result.Length - 2);
  1739. end;
  1740. end;
  1741. function SpQuotedStr(const str : string): string;
  1742. begin
  1743. Result := '''' + str + '''';
  1744. end;
  1745. function UnSpQuotedStr(const str: string) : string;
  1746. begin
  1747. Result := Trim(str);
  1748. if not Result.IsEmpty then
  1749. begin
  1750. if Result.StartsWith('''') then Result := Copy(Result, 2, Result.Length - 2);
  1751. end;
  1752. end;
  1753. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : string) : string;
  1754. begin
  1755. if aCondition then Result := aIfIsTrue else Result := aIfIsFalse;
  1756. end;
  1757. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Integer) : Integer;
  1758. begin
  1759. if aCondition then Result := aIfIsTrue else Result := aIfIsFalse;
  1760. end;
  1761. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Extended) : Extended;
  1762. begin
  1763. if aCondition then Result := aIfIsTrue else Result := aIfIsFalse;
  1764. end;
  1765. function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : TObject) : TObject;
  1766. begin
  1767. if aCondition then Result := aIfIsTrue else Result := aIfIsFalse;
  1768. end;
  1769. {$IFNDEF FPC}
  1770. {$IFNDEF DELPHIXE7_UP}
  1771. class procedure TArrayUtil<T>.Delete(var aArray : TArray<T>; aIndex : Integer);
  1772. var
  1773. n : Integer;
  1774. len : Integer;
  1775. begin
  1776. len := Length(aArray);
  1777. if (len > 0) and (aIndex < len) then
  1778. begin
  1779. for n := aIndex + 1 to len - 1 do aArray[n - 1] := aArray[n];
  1780. SetLength(aArray, len - 1);
  1781. end;
  1782. end;
  1783. {$ENDIF}
  1784. {$ENDIF}
  1785. {$IFNDEF NEXTGEN}
  1786. initialization
  1787. try
  1788. GetEnvironmentPaths;
  1789. except
  1790. {$IFDEF SHOW_ENVIRONMENTPATH_ERRORS}
  1791. on E : Exception do
  1792. begin
  1793. if not IsService then
  1794. begin
  1795. if HasConsoleOutput then Writeln(Format('[WARN] GetEnvironmentPaths: %s',[E.Message]))
  1796. else MessageBox(0,PWideChar(Format('Get environment path error: %s',[E.Message])),'GetEnvironmentPaths',MB_ICONEXCLAMATION);
  1797. end;
  1798. end;
  1799. {$ENDIF}
  1800. end;
  1801. {$ENDIF}
  1802. end.