source: ProjectTemplates/FileMenuProject/Packages/Common/UCommon.pas

Last change on this file was 507, checked in by chronos, 7 years ago
  • Modified: Update Common package.
  • Added: Support for color theme.
File size: 14.6 KB
Line 
1unit UCommon;
2
3{$mode delphi}
4
5interface
6
7uses
8 {$ifdef Windows}Windows,{$endif}
9 {$ifdef Linux}baseunix,{$endif}
10 Classes, SysUtils, StrUtils, Dialogs, Process, LCLIntf,
11 FileUtil; //, ShFolder, ShellAPI;
12
13type
14 TArrayOfByte = array of Byte;
15 TArrayOfString = array of string;
16 TExceptionEvent = procedure(Sender: TObject; E: Exception) of object;
17
18 TUserNameFormat = (
19 unfNameUnknown = 0, // Unknown name type.
20 unfNameFullyQualifiedDN = 1, // Fully qualified distinguished name
21 unfNameSamCompatible = 2, // Windows NT® 4.0 account name
22 unfNameDisplay = 3, // A "friendly" display name
23 unfNameUniqueId = 6, // GUID string that the IIDFromString function returns
24 unfNameCanonical = 7, // Complete canonical name
25 unfNameUserPrincipal = 8, // User principal name
26 unfNameCanonicalEx = 9,
27 unfNameServicePrincipal = 10, // Generalized service principal name
28 unfDNSDomainName = 11);
29
30 TFilterMethodMethod = function (FileName: string): Boolean of object;
31var
32 ExceptionHandler: TExceptionEvent;
33 DLLHandle1: HModule;
34
35{$IFDEF Windows}
36 GetUserNameEx: procedure (NameFormat: DWORD;
37 lpNameBuffer: LPSTR; nSize: PULONG); stdcall;
38{$ENDIF}
39
40function IntToBin(Data: Int64; Count: Byte): string;
41function BinToInt(BinStr: string): Int64;
42function TryHexToInt(Data: string; var Value: Integer): Boolean;
43function TryBinToInt(Data: string; var Value: Integer): Boolean;
44function BinToHexString(Source: AnsiString): string;
45//function DelTree(DirName : string): Boolean;
46//function GetSpecialFolderPath(Folder: Integer): string;
47function BCDToInt(Value: Byte): Byte;
48function CompareByteArray(Data1, Data2: TArrayOfByte): Boolean;
49function GetUserName: string;
50function LoggedOnUserNameEx(Format: TUserNameFormat): string;
51function SplitString(var Text: string; Count: Word): string;
52function GetBitCount(Variable: QWord; MaxIndex: Integer): Integer;
53function GetBit(Variable: QWord; Index: Byte): Boolean;
54procedure SetBit(var Variable: Int64; Index: Byte; State: Boolean); overload;
55procedure SetBit(var Variable: QWord; Index: Byte; State: Boolean); overload;
56procedure SetBit(var Variable: Cardinal; Index: Byte; State: Boolean); overload;
57procedure SetBit(var Variable: Word; Index: Byte; State: Boolean); overload;
58function AddLeadingZeroes(const aNumber, Length : integer) : string;
59function LastPos(const SubStr: String; const S: String): Integer;
60function GenerateNewName(OldName: string): string;
61function GetFileFilterItemExt(Filter: string; Index: Integer): string;
62procedure FileDialogUpdateFilterFileType(FileDialog: TOpenDialog);
63procedure DeleteFiles(APath, AFileSpec: string);
64procedure OpenWebPage(URL: string);
65procedure OpenFileInShell(FileName: string);
66procedure ExecuteProgram(Executable: string; Parameters: array of string);
67procedure FreeThenNil(var Obj);
68function RemoveQuotes(Text: string): string;
69function ComputerName: string;
70function OccurenceOfChar(What: Char; Where: string): Integer;
71function GetDirCount(Dir: string): Integer;
72function MergeArray(A, B: array of string): TArrayOfString;
73function LoadFileToStr(const FileName: TFileName): AnsiString;
74procedure SearchFiles(AList: TStrings; Dir: string;
75 FilterMethod: TFilterMethodMethod);
76
77
78implementation
79
80function BinToInt(BinStr : string) : Int64;
81var
82 i : byte;
83 RetVar : Int64;
84begin
85 BinStr := UpperCase(BinStr);
86 if BinStr[length(BinStr)] = 'B' then Delete(BinStr,length(BinStr),1);
87 RetVar := 0;
88 for i := 1 to length(BinStr) do begin
89 if not (BinStr[i] in ['0','1']) then begin
90 RetVar := 0;
91 Break;
92 end;
93 RetVar := (RetVar shl 1) + (byte(BinStr[i]) and 1) ;
94 end;
95
96 Result := RetVar;
97end;
98
99function BinToHexString(Source: AnsiString): string;
100var
101 I: Integer;
102begin
103 for I := 1 to Length(Source) do begin
104 Result := Result + LowerCase(IntToHex(Ord(Source[I]), 2));
105 end;
106end;
107
108
109procedure DeleteFiles(APath, AFileSpec: string);
110var
111 SearchRec: TSearchRec;
112 Find: Integer;
113 Path: string;
114begin
115 Path := IncludeTrailingPathDelimiter(APath);
116
117 Find := FindFirst(Path + AFileSpec, faAnyFile xor faDirectory, SearchRec);
118 while Find = 0 do begin
119 DeleteFile(Path + SearchRec.Name);
120
121 Find := SysUtils.FindNext(SearchRec);
122 end;
123 FindClose(SearchRec);
124end;
125
126
127function GetFileFilterItemExt(Filter: string; Index: Integer): string;
128var
129 List: TStringList;
130begin
131 try
132 List := TStringList.Create;
133 List.Text := StringReplace(Filter, '|', #10, [rfReplaceAll]);
134 Result := List[Index * 2 + 1];
135 finally
136 List.Free;
137 end;
138end;
139
140procedure FileDialogUpdateFilterFileType(FileDialog: TOpenDialog);
141var
142 FileExt: string;
143begin
144 FileExt := GetFileFilterItemExt(FileDialog.Filter, FileDialog.FilterIndex - 1);
145 Delete(FileExt, 1, 1); // Remove symbol '*'
146 if FileExt <> '.*' then
147 FileDialog.FileName := ChangeFileExt(FileDialog.FileName, FileExt)
148end;
149
150function GenerateNewName(OldName: string): string;
151var
152 I: Integer;
153 Number: Integer;
154begin
155 Number := 1;
156 // Find number on end
157 if Length(OldName) > 0 then begin
158 I := Length(OldName);
159 while (I > 1) and ((OldName[I] >= '0') and (OldName[I] <= '9')) do Dec(I);
160 TryStrToInt(Copy(OldName, I + 1, Length(OldName) - I), Number);
161 Inc(Number)
162 end;
163 Result := Copy(OldName, 1, I) + IntToStr(Number);
164end;
165
166(*function DelTree(DirName : string): Boolean;
167var
168 SHFileOpStruct : TSHFileOpStruct;
169 DirBuf : array [0..255] of char;
170begin
171 DirName := UTF8Decode(DirName);
172 try
173 Fillchar(SHFileOpStruct,Sizeof(SHFileOpStruct),0) ;
174 FillChar(DirBuf, Sizeof(DirBuf), 0 ) ;
175 StrPCopy(DirBuf, DirName) ;
176 with SHFileOpStruct do begin
177 Wnd := 0;
178 pFrom := @DirBuf;
179 wFunc := FO_DELETE;
180 fFlags := FOF_ALLOWUNDO;
181 fFlags := fFlags or FOF_NOCONFIRMATION;
182 fFlags := fFlags or FOF_SILENT;
183 end;
184 Result := (SHFileOperation(SHFileOpStruct) = 0) ;
185 except
186 Result := False;
187 end;
188end;*)
189
190function LastPos(const SubStr: String; const S: String): Integer;
191begin
192 Result := Pos(ReverseString(SubStr), ReverseString(S));
193 if (Result <> 0) then
194 Result := ((Length(S) - Length(SubStr)) + 1) - Result + 1;
195end;
196
197function BCDToInt(Value: Byte): Byte;
198begin
199 Result := (Value shr 4) * 10 + (Value and 15);
200end;
201
202(*function GetSpecialFolderPath(Folder: Integer): string;
203const
204 SHGFP_TYPE_CURRENT = 0;
205var
206 Path: array[0..MAX_PATH] of Char;
207begin
208 Result := 'C:\Test';
209 if SUCCEEDED(SHGetFolderPath(0, Folder, 0, SHGFP_TYPE_CURRENT, @path[0])) then
210 Result := path
211 else
212 Result := '';
213end;*)
214
215function IntToBin(Data: Int64; Count: Byte): string;
216var
217 I: Integer;
218begin
219 Result := '';
220 for I := 0 to Count - 1 do
221 Result := IntToStr((Data shr I) and 1) + Result;
222end;
223
224function IntToHex(Data: Cardinal; Count: Byte): string;
225const
226 Chars: array[0..15] of Char = '0123456789ABCDEF';
227var
228 I: Integer;
229begin
230 Result := '';
231 for I := 0 to Count - 1 do
232 Result := Result + Chars[(Data shr (I * 4)) and 15];
233end;
234
235function TryHexToInt(Data: string; var Value: Integer): Boolean;
236var
237 I: Integer;
238begin
239 Data := UpperCase(Data);
240 Result := True;
241 Value := 0;
242 for I := 0 to Length(Data) - 1 do begin
243 if (Data[I + 1] >= '0') and (Data[I + 1] <= '9') then
244 Value := Value or (Ord(Data[I + 1]) - Ord('0')) shl ((Length(Data) - I - 1) * 4)
245 else if (Data[I + 1] >= 'A') and (Data[I + 1] <= 'F') then
246 Value := Value or (Ord(Data[I + 1]) - Ord('A') + 10) shl ((Length(Data) - I - 1) * 4)
247 else Result := False;
248 end;
249end;
250
251function TryBinToInt(Data: string; var Value: Integer): Boolean;
252var
253 I: Integer;
254begin
255 Result := True;
256 Value := 0;
257 for I := 0 to Length(Data) - 1 do begin
258 if (Data[I + 1] >= '0') and (Data[I + 1] <= '1') then
259 Value := Value or (Ord(Data[I + 1]) - Ord('0')) shl ((Length(Data) - I - 1))
260 else Result := False;
261 end;
262end;
263
264function CompareByteArray(Data1, Data2: TArrayOfByte): Boolean;
265var
266 I: Integer;
267begin
268 if Length(Data1) = Length(Data2) then begin
269 Result := True;
270 for I := 0 to Length(Data1) - 1 do begin
271 if Data1[I] <> Data2[I] then begin
272 Result := False;
273 Break;
274 end
275 end;
276 end else Result := False;
277end;
278
279function Explode(Separator: char; Data: string): TArrayOfString;
280begin
281 SetLength(Result, 0);
282 while Pos(Separator, Data) > 0 do begin
283 SetLength(Result, Length(Result) + 1);
284 Result[High(Result)] := Copy(Data, 1, Pos(Separator, Data) - 1);
285 Delete(Data, 1, Pos(Separator, Data));
286 end;
287 SetLength(Result, Length(Result) + 1);
288 Result[High(Result)] := Data;
289end;
290
291{$IFDEF Windows}
292function GetUserName: string;
293const
294 MAX_USERNAME_LENGTH = 256;
295var
296 L: LongWord;
297begin
298 L := MAX_USERNAME_LENGTH + 2;
299 SetLength(Result, L);
300 if Windows.GetUserName(PChar(Result), L) and (L > 0) then begin
301 SetLength(Result, StrLen(PChar(Result)));
302 Result := UTF8Encode(Result);
303 end else Result := '';
304end;
305
306function GetVersionInfo: TOSVersionInfo;
307begin
308 Result.dwOSVersionInfoSize := SizeOf(Result);
309 if GetVersionEx(Result) then begin
310 end;
311end;
312{$endif}
313
314function ComputerName: string;
315{$ifdef mswindows}
316const
317 INFO_BUFFER_SIZE = 32767;
318var
319 Buffer : array[0..INFO_BUFFER_SIZE] of WideChar;
320 Ret : DWORD;
321begin
322 Ret := INFO_BUFFER_SIZE;
323 If (GetComputerNameW(@Buffer[0],Ret)) then begin
324 Result := UTF8Encode(WideString(Buffer));
325 end
326 else begin
327 Result := 'ERROR_NO_COMPUTERNAME_RETURNED';
328 end;
329end;
330{$endif}
331{$ifdef unix}
332var
333 Name: UtsName;
334begin
335 fpuname(Name);
336 Result := Name.Nodename;
337end;
338{$endif}
339
340{$ifdef windows}
341function LoggedOnUserNameEx(Format: TUserNameFormat): string;
342const
343 MaxLength = 1000;
344var
345 UserName: array[0..MaxLength] of Char;
346 VersionInfo: TOSVersionInfo;
347 Size: DWORD;
348begin
349 VersionInfo := GetVersionInfo;
350 if VersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT then begin
351 Size := MaxLength;
352 GetUserNameEx(Integer(Format), @UserName, @Size);
353 //ShowMessage(SysErrorMessage(GetLastError));
354 if GetLastError = 0 then Result := UTF8Encode(UserName)
355 else Result := GetUserName;
356 end else Result := GetUserName;
357end;
358{$ELSE}
359function GetUserName: string;
360begin
361 Result := '';
362end;
363
364function LoggedOnUserNameEx(Format: TUserNameFormat): string;
365begin
366 Result := '';
367end;
368
369{$ENDIF}
370
371function SplitString(var Text: string; Count: Word): string;
372begin
373 Result := Copy(Text, 1, Count);
374 Delete(Text, 1, Count);
375end;
376
377function GetBitCount(Variable: QWord; MaxIndex: Integer): Integer;
378var
379 I: Integer;
380begin
381 Result := 0;
382 for I := 0 to MaxIndex - 1 do
383 if ((Variable shr I) and 1) = 1 then Inc(Result);
384end;
385
386function GetBit(Variable:QWord;Index:Byte):Boolean;
387begin
388 Result := ((Variable shr Index) and 1) = 1;
389end;
390
391procedure SetBit(var Variable: Int64; Index: Byte; State: Boolean);
392begin
393 Variable := (Variable and ((1 shl Index) xor High(QWord))) or (Int64(State) shl Index);
394end;
395
396procedure SetBit(var Variable:QWord;Index:Byte;State:Boolean); overload;
397begin
398 Variable := (Variable and ((1 shl Index) xor High(QWord))) or (QWord(State) shl Index);
399end;
400
401procedure SetBit(var Variable:Cardinal;Index:Byte;State:Boolean); overload;
402begin
403 Variable := (Variable and ((1 shl Index) xor High(Cardinal))) or (Cardinal(State) shl Index);
404end;
405
406procedure SetBit(var Variable:Word;Index:Byte;State:Boolean); overload;
407begin
408 Variable := (Variable and ((1 shl Index) xor High(Word))) or (Word(State) shl Index);
409end;
410
411function AddLeadingZeroes(const aNumber, Length : integer) : string;
412begin
413 Result := SysUtils.Format('%.*d', [Length, aNumber]) ;
414end;
415
416procedure LoadLibraries;
417begin
418 {$IFDEF Windows}
419 DLLHandle1 := LoadLibrary('secur32.dll');
420 if DLLHandle1 <> 0 then
421 begin
422 @GetUserNameEx := GetProcAddress(DLLHandle1, 'GetUserNameExA');
423 end;
424 {$ENDIF}
425end;
426
427procedure FreeLibraries;
428begin
429 {$IFDEF Windows}
430 if DLLHandle1 <> 0 then FreeLibrary(DLLHandle1);
431 {$ENDIF}
432end;
433
434procedure ExecuteProgram(Executable: string; Parameters: array of string);
435var
436 Process: TProcess;
437 I: Integer;
438begin
439 try
440 Process := TProcess.Create(nil);
441 Process.Executable := Executable;
442 for I := 0 to Length(Parameters) - 1 do
443 Process.Parameters.Add(Parameters[I]);
444 Process.Options := [poNoConsole];
445 Process.Execute;
446 finally
447 Process.Free;
448 end;
449end;
450
451procedure FreeThenNil(var Obj);
452begin
453 TObject(Obj).Free;
454 TObject(Obj) := nil;
455end;
456
457procedure OpenWebPage(URL: string);
458begin
459 OpenURL(URL);
460end;
461
462procedure OpenFileInShell(FileName: string);
463begin
464 ExecuteProgram('cmd.exe', ['/c', 'start', FileName]);
465end;
466
467function RemoveQuotes(Text: string): string;
468begin
469 Result := Text;
470 if (Pos('"', Text) = 1) and (Text[Length(Text)] = '"') then
471 Result := Copy(Text, 2, Length(Text) - 2);
472end;
473
474function OccurenceOfChar(What: Char; Where: string): Integer;
475var
476 I: Integer;
477begin
478 Result := 0;
479 for I := 1 to Length(Where) do
480 if Where[I] = What then Inc(Result);
481end;
482
483function GetDirCount(Dir: string): Integer;
484begin
485 Result := OccurenceOfChar(DirectorySeparator, Dir);
486 if Copy(Dir, Length(Dir), 1) = DirectorySeparator then
487 Dec(Result);
488end;
489
490function MergeArray(A, B: array of string): TArrayOfString;
491var
492 I: Integer;
493begin
494 SetLength(Result, Length(A) + Length(B));
495 for I := 0 to Length(A) - 1 do
496 Result[I] := A[I];
497 for I := 0 to Length(B) - 1 do
498 Result[Length(A) + I] := B[I];
499end;
500
501function LoadFileToStr(const FileName: TFileName): AnsiString;
502var
503 FileStream: TFileStream;
504 Read: Integer;
505begin
506 Result := '';
507 FileStream := TFileStream.Create(FileName, fmOpenRead);
508 try
509 if FileStream.Size > 0 then begin
510 SetLength(Result, FileStream.Size);
511 Read := FileStream.Read(Pointer(Result)^, FileStream.Size);
512 SetLength(Result, Read);
513 end;
514 finally
515 FileStream.Free;
516 end;
517end;
518
519function DefaultSearchFilter(const FileName: string): Boolean;
520begin
521 Result := True;
522end;
523
524procedure SearchFiles(AList: TStrings; Dir: string;
525 FilterMethod: TFilterMethodMethod);
526var
527 SR: TSearchRec;
528begin
529 Dir := IncludeTrailingPathDelimiter(Dir);
530 if FindFirst(Dir + '*', faAnyFile, SR) = 0 then
531 try
532 repeat
533 if (SR.Name = '.') or (SR.Name = '..') or not FilterMethod(SR.Name) then Continue;
534 AList.Add(Dir + SR.Name);
535 if (SR.Attr and faDirectory) <> 0 then
536 SearchFiles(AList, Dir + SR.Name, FilterMethod);
537 until FindNext(SR) <> 0;
538 finally
539 FindClose(SR);
540 end;
541end;
542
543
544initialization
545
546LoadLibraries;
547
548
549finalization
550
551FreeLibraries;
552
553end.
Note: See TracBrowser for help on using the repository browser.