unit DEngFileWatcher;

interface

uses
  {$IFDEF WINDOWS}windows,{$ENDIF}
  dobjects;

type
TFileWatcher = object
private
  {$IFDEF WINDOWS}
  FLastWriteTime: windows.TFileTime;
  {$ENDIF}
  FFileName: AnsiString;
public
  constructor Init(const FileName: AnsiString = '');
  destructor Done; virtual;
  procedure SetFileName(const FileName: AnsiString = '');
  function PopFileChanged: Boolean;
  property FileName: AnsiString read FFileName write SetFileName;
end;

implementation

constructor TFileWatcher.Init(const FileName: AnsiString = '');
begin
  SetFileName(FileName);
end;

destructor TFileWatcher.Done;
begin
  SetFileName('');
end;

procedure TFileWatcher.SetFileName(const FileName: AnsiString = '');
begin
  // Set new file name
  FFileName := FileName;
  if FFileName = '' then
    Exit;

  PopFileChanged;
end;

function TFileWatcher.PopFileChanged: Boolean;
{$IFDEF WINDOWS}
var
  FindData: windows.TWin32FindData;
  Handle: windows.THandle;
{$ENDIF}
begin
  if FFileName = '' then
    Exit(False);

{$IFDEF WINDOWS}
  Handle := windows.FindFirstFileA(@FileName[1], FindData);
  if Handle <> INVALID_HANDLE_VALUE then begin
    windows.FindClose(Handle);
    if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin
      Result := (FindData.ftLastWriteTime.dwLowDateTime <> FLastWriteTime.dwLowDateTime)
             or (FindData.ftLastWriteTime.dwHighDateTime <> FLastWriteTime.dwHighDateTime);
      if Result then
        FLastWriteTime := FindData.ftLastWriteTime;
      Exit;
    end else
      Exit(False);
  end;
  Exit(False);
{$ELSE}
  Result := False;
{$ENDIF}
end;

end.
