1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
|
{%MainUnit lazfileutils.pas}
function ReadAllLinks(const Filename: string;
ExceptionOnError: boolean): string;
begin
// not supported under Windows
Result:=Filename;
end;
function GetPhysicalFilename(const Filename: string;
OnError: TPhysicalFilenameOnError): string;
begin
if OnError=pfeEmpty then ;
Result:=Filename;
end;
// ******** Start of WideString specific implementations ************
function GetCurrentDirUtf8: String;
var
U: UnicodeString;
begin
System.GetDir(0, U{%H-});
// Need to do an explicit encode to utf8, if compiled with "-dDisableUtf8RTL"
Result := {%H-}U;
end;
procedure GetDirUtf8(DriveNr: Byte; var Dir: String);
var
U: UnicodeString;
begin
{$PUSH}
{$IOCHECKS OFF}
GetDir(DriveNr, U{%H-});
if IOResult <> 0 then
U := UnicodeString(Chr(DriveNr + Ord('A') - 1) + ':\');
{$POP}
// Need to do an explicit encode to utf8, if compiled with "-dDisableUtf8RTL"
Dir := {%H-}U;
end;
function FileOpenUtf8(Const FileName : string; Mode : Integer) : THandle;
begin
Result := SysUtils.FileOpen(FileName, Mode);
end;
function FileCreateUTF8(Const FileName : string) : THandle;
begin
Result := FileCreateUtf8(FileName, fmShareExclusive, 0);
end;
function FileCreateUTF8(Const FileName : string; Rights: Cardinal) : THandle;
begin
Result := FileCreateUtf8(FileName, fmShareExclusive, Rights);
end;
function FileCreateUtf8(Const FileName : string; ShareMode: Integer; Rights: Cardinal) : THandle;
begin
Result := SysUtils.FileCreate(FileName, ShareMode, Rights);
end;
function FileGetAttrUtf8(const FileName: String): Longint;
begin
Result := SysUtils.FileGetAttr(FileName);
end;
function FileSetAttrUtf8(const Filename: String; Attr: longint): Longint;
begin
Result := SysUtils.FileSetAttr(FileName, Attr);
end;
function FileAgeUtf8(const FileName: String): Longint;
begin
Result := SysUtils.FileAge(FileName);
end;
function FileSetDateUtf8(const FileName: String; Age: Longint): Longint;
begin
Result := SysUtils.FileSetDate(FileName, Age);
end;
function FileSizeUtf8(const Filename: string): int64;
var
R: TSearchRec;
begin
if SysUtils.FindFirst(FileName, faAnyFile, R) = 0 then
begin
Result := R.Size;
SysUtils.FindClose(R);
end
else
Result := -1;
end;
function CreateDirUtf8(const NewDir: String): Boolean;
begin
Result := SysUtils.CreateDir(NewDir);
end;
function RemoveDirUtf8(const Dir: String): Boolean;
begin
Result := SysUtils.RemoveDir(Dir);
end;
function DeleteFileUtf8(const FileName: String): Boolean;
begin
Result := SysUtils.DeleteFile(FileName);
end;
function RenameFileUtf8(const OldName, NewName: String): Boolean;
begin
Result := SysUtils.RenameFile(OldName, NewName);
end;
function SetCurrentDirUtf8(const NewDir: String): Boolean;
begin
{$ifdef WinCE}
raise Exception.Create('[SetCurrentDirWide] The concept of the current directory doesn''t exist in Windows CE');
{$else}
Result:=Windows.SetCurrentDirectoryW(PWidechar(UnicodeString(NewDir)));
{$endif}
end;
function FindFirstUtf8(const Path: string; Attr: Longint; out Rslt: TSearchRec): Longint;
begin
Result := SysUtils.FindFirst(Path, Attr, Rslt);
end;
function FindNextUtf8(var Rslt: TSearchRec): Longint;
begin
Result := SysUtils.FindNext(Rslt);
end;
{$IFDEF WINCE}
// In WinCE these API calls are in Windows unit
function SHGetFolderPathUTF8(ID : Integer) : String;
Var
APath : Array[0..MAX_PATH] of WideChar;
WS: WideString;
Len: SizeInt;
begin
Result := '';
if SHGetSpecialFolderPath(0, APath, ID, True) then
begin
Len := StrLen(APath);
SetLength(WS, Len);
System.Move(APath[0], WS[1], Len * SizeOf(WideChar));
Result := AppendPathDelim(Utf16ToUtf8(WS));
end
else
Result:='';
end;
{$ELSE}
Type
PFNSHGetFolderPathW = Function(Ahwnd: HWND; Csidl: Integer; Token: THandle; Flags: DWord; Path: PWChar): HRESULT; stdcall;
var
SHGetFolderPathW : PFNSHGetFolderPathW = Nil;
CFGDLLHandle : THandle = 0;
Procedure InitDLL;
Var
pathBuf: array[0..MAX_PATH-1] of char;
pathLength: Integer;
begin
{ Load shfolder.dll using a full path, in order to prevent spoofing (Mantis #18185)
Don't bother loading shell32.dll because shfolder.dll itself redirects SHGetFolderPath
to shell32.dll whenever possible. }
pathLength:=GetSystemDirectory(pathBuf, MAX_PATH);
if (pathLength>0) and (pathLength<MAX_PATH-14) then { 14=length('\shfolder.dll'#0) }
begin
StrLCopy(@pathBuf[pathLength],'\shfolder.dll',MAX_PATH-pathLength-1);
CFGDLLHandle:=LoadLibrary(pathBuf);
if (CFGDLLHandle<>0) then
begin
Pointer(ShGetFolderPathW):=GetProcAddress(CFGDLLHandle,'SHGetFolderPathW');
If @ShGetFolderPathW=nil then
begin
FreeLibrary(CFGDLLHandle);
CFGDllHandle:=0;
end;
end;
end;
If (@ShGetFolderPathW=Nil) then
Raise Exception.Create('Could not determine SHGetFolderPathW Function');
end;
function SHGetFolderPathUTF8(ID : Integer) : String;
Var
APath : Array[0..MAX_PATH] of WideChar;
WS: WideString;
Len: SizeInt;
begin
Result := '';
if (CFGDLLHandle = 0) then
InitDLL;
If (SHGetFolderPathW <> Nil) then
begin
FillChar(APath{%H-}, SizeOf(APath), #0);
if SHGetFolderPathW(0,ID or CSIDL_FLAG_CREATE,0,0,@APATH[0]) = S_OK then
begin
Len := StrLen(APath);
SetLength(WS, Len);
System.Move(APath[0], WS[1], Len * SizeOf(WideChar));
Result := AppendPathDelim(Utf16ToUtf8(WS));
end;
end
else
Result := SysToUtf8(GetWindowsSpecialDir(ID));
end;
{$ENDIF WINCE}
function DGetAppConfigDir({%H-}Global : Boolean) : String;
begin
Result := ChompPathDelim(ExtractFilePath(ParamStrUtf8(0)));
end;
function GetAppConfigDirUtf8(Global: Boolean; Create: boolean = false): string;
const
CSIDL_GLOBAL = {$IFDEF WINCE}CSIDL_WINDOWS{$ELSE}CSIDL_COMMON_APPDATA{$ENDIF WINCE};
CSIDL_LOCAL = {$IFDEF WINCE}CSIDL_APPDATA{$ELSE}CSIDL_LOCAL_APPDATA{$ENDIF};
begin
If Global then
Result := SHGetFolderPathUTF8(CSIDL_GLOBAL)
else
Result := SHGetFolderPathUTF8(CSIDL_LOCAL);
If (Result <> '') then
begin
if VendorName <> '' then
Result := AppendPathDelim(Result + VendorName);
Result := AppendPathDelim(Result + ApplicationName);
end
else
Result := AppendPathDelim(DGetAppConfigDir(Global));
if Result = '' then exit;
if Create and not ForceDirectoriesUtf8(Result) then
raise EInOutError.Create(Format(lrsUnableToCreateConfigDirectoryS,[Result]));
end;
function GetAppConfigFileUtf8(Global: Boolean; SubDir: boolean;
CreateDir: boolean): string;
var
Dir: string;
begin
Result := GetAppConfigDirUtf8(Global);
if SubDir then
Result := AppendPathDelim(Result + 'Config');
Result := Result + ApplicationName + ConfigExtension;
if not CreateDir then exit;
Dir := ExtractFilePath(Result);
if Dir = '' then exit;
if not ForceDirectoriesUTF8(Dir) then
raise EInOutError.Create(Format(lrsUnableToCreateConfigDirectoryS,[Dir]));
end;
function GetShellLinkTarget(const FileName: string): string;
{$IFnDEF WINCE}
var
ShellLinkW: IShellLinkW;
PersistFile: IPersistFile;
WideFileName: WideString;
WidePath: array [0 .. MAX_PATH] of WideChar;
WinFindData: WIN32_FIND_DATAW;
{$ENDIF WINCE}
begin
Result := FileName;
{$IFnDEF WINCE}
if (LowerCase(ExtractFileExt(FileName)) = '.lnk') then
begin
if (CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER,
IShellLinkW, ShellLinkW) = S_OK) then
if (ShellLinkW.QueryInterface(IPersistFile, PersistFile) = S_OK) then
begin
WideFileName := Utf8ToUtf16(FileName);
FillChar(WinFindData{%H-}, SizeOf(WinFindData), 0);
if (PersistFile.Load(POleStr(WideFileName), STGM_READ) = S_OK) then
begin
if (ShellLinkW.GetPath(WidePath, Length(WidePath),
@WinFindData, SLGP_UNCPRIORITY) = S_OK) then
begin
Result := Utf16toUtf8(WidePath); // implicit conversion
end;
end;
end;
end;
{$ENDIF WINCE}
end;
// ******** End of WideString specific implementations ************
function FilenameIsAbsolute(const TheFilename: string):boolean;
begin
Result:=FilenameIsWinAbsolute(TheFilename);
end;
function ExpandFileNameUtf8(const FileName: string; {const} BaseDir: String = ''): String;
var
IsAbs, StartsWithRoot, CanUseBaseDir : Boolean;
{$ifndef WinCE}
HasDrive: Boolean;
FnDrive, CurDrive, BaseDirDrive: Char;
{$endif}
CurDir, Fn: String;
begin
//writeln('LazFileUtils.ExpandFileNameUtf8');
//writeln('FileName = "',FileName,'"');
//writeln('BaseDir = "',BaseDir,'"');
Fn := FileName;
//if Filename uses ExtendedLengthPath scheme then it cannot be expanded
//AND it should not be altered by ForcePathDelims or ResolveDots
//See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
if (Length(Fn) > 3) and (Fn[1] = PathDelim) and (Fn[2] = PathDelim) and
(Fn[3] = '?') and (Fn[4] = PathDelim) //Do NOT use AllowDirectorySeparators here!
then Exit(Fn);
ForcePathDelims(Fn);
IsAbs := FileNameIsWinAbsolute(Fn);
if not IsAbs then
begin
StartsWithRoot := (Fn = '\') or
((Length(Fn) > 1) and
(Fn[1] = DirectorySeparator) and
(Fn[2] <> DirectorySeparator));
{$ifndef WinCE}
HasDrive := (Length(Fn) > 1) and
(Fn[2] = ':') and
(UpCase(Fn[1]) in ['A'..'Z']);
if HasDrive then
begin
FnDrive := UpCase(Fn[1]);
GetDirUtf8(Byte(FnDrive)-64, CurDir{%H-});
CurDrive := UpCase(GetCurrentDirUtf8[1]);
end
else
begin
CurDir := GetCurrentDirUtf8;
FnDrive := UpCase(CurDir[1]);
CurDrive := FnDrive;
end;
//writeln('HasDrive = ',HasDrive,' Fn = ',Fn);
//writeln('CurDir = ',CurDir);
//writeln('CurDrive = ',CurDrive);
//writeln('FnDrive = ',FnDrive);
if (Length(BaseDir) > 1) and (UpCase(BaseDir[1]) in ['A'..'Z']) and (BaseDir[2] = ':') then
begin
BaseDirDrive := BaseDir[1]
end
else
begin
if HasDrive then
BaseDirDrive := CurDrive
else
BaseDirDrive := #0;
end;
//You cannot use BaseDir if both FileName and BaseDir includes a drive and they are not the same
CanUseBaseDir := ((BaseDirDrive = #0) or
(not HasDrive) or
(HasDrive and (FnDrive = BaseDirDrive)))
and (BaseDir <> '');
//writeln('CanUseBaseDir = ',CanUseBaseDir);
if not HasDrive and StartsWithRoot and not CanUseBaseDir then
begin
//writeln('HasDrive and StartsWithRoot');
Fn := Copy(CurDir,1,2) + Fn;
HasDrive := True;
IsAbs := True;
end;
//FileNames like C:foo, strip Driveletter + colon
if HasDrive and not IsAbs then Delete(Fn,1,2);
//writeln('HasDrive = ',Hasdrive,' Fn = ',Fn);
{$else}
CanUseBaseDir := True;
{$endif WinCE}
end;
if IsAbs then
begin
//writeln('IsAbs = True -> Exit');
Result := ResolveDots(Fn);
end
else
begin
if not CanUseBaseDir or (BaseDir = '') then
Fn := IncludeTrailingPathDelimiter(CurDir) + Fn
else
begin
if (Length(Fn) > 0) and (Fn[1] = DirectorySeparator) then Delete(Fn,1,1);
Fn := IncludeTrailingPathDelimiter(BaseDir) + Fn;
end;
Fn := ResolveDots(Fn);
//if BaseDir is something like 'z:foo\' or '\' then this needs to be expanded as well
if not FileNameIsAbsolute(Fn) then
Fn := ExpandFileNameUtf8(Fn, '');
Result := Fn;
end;
end;
function FileExistsUTF8(const Filename: string): boolean;
begin
Result := SysUtils.FileExists(Filename);
end;
function DirectoryExistsUTF8(const Directory: string): boolean;
begin
Result := SysUtils.DirectoryExists(Directory);
end;
function FileIsExecutable(const AFilename: string): boolean;
begin
Result:=FileExistsUTF8(AFilename);
end;
procedure CheckIfFileIsExecutable(const AFilename: string);
begin
// TProcess does not report, if a program can not be executed
// to get good error messages consider the OS
if not FileExistsUTF8(AFilename) then begin
raise Exception.Create(Format(lrsFileDoesNotExist, [AFilename]));
end;
if DirPathExists(AFilename) then begin
raise Exception.Create(Format(lrsFileIsADirectoryAndNotAnExecutable, [
AFilename]));
end;
end;
function FileIsSymlink(const AFilename: string): boolean;
{$ifndef wince}
const
IO_REPARSE_TAG_MOUNT_POINT = $A0000003;
IO_REPARSE_TAG_SYMLINK = $A000000C;
var
Attr: Longint;
Rec: TSearchRec;
{$endif}
begin
{$ifndef wince}
Attr := FileGetAttrUTF8(AFilename);
if (Attr <> -1) and (Attr and FILE_ATTRIBUTE_REPARSE_POINT <> 0) then
begin
FindFirstUTF8(AFilename, Attr, Rec);
if Rec.FindHandle <> feInvalidHandle then
begin
Windows.FindClose(Rec.FindHandle);
Result := (Rec.FindData.dwReserved0 = IO_REPARSE_TAG_SYMLINK) or (Rec.FindData.dwReserved0 = IO_REPARSE_TAG_MOUNT_POINT);
end
else
Result := False;
end
else
{$endif}
Result := False;
end;
procedure CheckIfFileIsSymlink(const AFilename: string);
begin
// to get good error messages consider the OS
if not FileExistsUTF8(AFilename) then begin
raise Exception.Create(Format(lrsFileDoesNotExist, [AFilename]));
end;
if not FileIsSymLink(AFilename) then
raise Exception.Create(Format(lrsIsNotASymbolicLink, [AFilename]));
end;
function FileIsHardLink(const AFilename: string): boolean;
{$ifndef wince}
var
H: THandle;
FileInfo: BY_HANDLE_FILE_INFORMATION;
{$endif}
begin
Result := false;
{$ifndef wince}
//HardLinks are not supported in Win9x platform
if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) then Exit;
H := FileOpenUtf8(aFilename, fmOpenRead);
if (H <> feInvalidHandle) then
begin
FillChar(FileInfo{%H-}, SizeOf(BY_HANDLE_FILE_INFORMATION),0);
if GetFileInformationByHandle(H, FileInfo) then
Result := (FileInfo.nNumberOfLinks > 1);
FileClose(H);
end;
{$endif}
end;
function FileIsReadable(const AFilename: string): boolean;
begin
Result:=FileExistsUTF8(AFilename);
end;
function FileIsWritable(const AFilename: string): boolean;
begin
Result := ((FileGetAttrUTF8(AFilename) and faReadOnly) = 0);
end;
function IsUNCPath(const Path: String): Boolean;
begin
Result := (Length(Path) > 2) and (Path[1] in AllowDirectorySeparators) and (Path[2] in AllowDirectorySeparators);
end;
function ExtractUNCVolume(const Path: String): String;
var
I, Len: Integer;
// the next function reuses Len variable
function NextPathDelim(const Start: Integer): Integer;// inline;
begin
Result := Start;
while (Result <= Len) and not (Path[Result] in AllowDirectorySeparators) do
inc(Result);
end;
begin
if not IsUNCPath(Path) then
Exit('');
I := 3;
Len := Length(Path);
if Path[I] = '?' then
begin
// Long UNC path form like:
// \\?\UNC\ComputerName\SharedFolder\Resource or
// \\?\C:\Directory
inc(I);
if not (Path[I] in AllowDirectorySeparators) then
Exit('');
if UpperCase(Copy(Path, I + 1, 3)) = 'UNC' then
begin
inc(I, 4);
if I < Len then
I := NextPathDelim(I + 1);
if I < Len then
I := NextPathDelim(I + 1);
end;
end
else
begin
I := NextPathDelim(I);
if I < Len then
I := NextPathDelim(I + 1);
end;
Result := Copy(Path, 1, I);
end;
function GetFileDescription(const AFilename: string): string;
begin
// date + time
Result:=lrsModified;
try
Result:=Result+FormatDateTime('DD/MM/YYYY hh:mm',
FileDateToDateTime(FileAgeUTF8(AFilename)));
except
Result:=Result+'?';
end;
end;
procedure InitLazFileUtils;
begin
end;
procedure FinalizeLazFileUtils;
begin
{$IFnDEF WINCE}
if CFGDLLHandle <> 0 then
FreeLibrary(CFGDllHandle);
{$ENDIF WINCE}
end;
|