source: trunk/Packages/Common/UCommon.pas

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