Quick.Commons.pas 53 KB

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