summaryrefslogtreecommitdiff
path: root/plugins/!Deprecated/MirandaNGHistoryToDB/FSMonitor.pas
blob: b19cde322f5c57a040d72a49dc361a67717127c5 (plain)
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
{ ############################################################################ }
{ #                                                                          # }
{ #  MirandaNG HistoryToDB Plugin v2.5                                       # }
{ #                                                                          # }
{ #  License: GPLv3                                                          # }
{ #                                                                          # }
{ #  Author: Grigorev Michael (icq: 161867489, email: sleuthhound@gmail.com) # }
{ #                                                                          # }
{ ############################################################################ }

unit FSMonitor;

{$I jedi.inc}

interface

type
  // Ñòðóêòóðà ñ èíôîðìàöèåé îá èçìåíåíèè â ôàéëîâîé ñèñòåìå (ïåðåäàåòñÿ â callback ïðîöåäóðó)
  PInfoCallBack = ^TInfoCallBack;
  TInfoCallBack = record
    FAction      : Integer; // Òèï èçìåíåíèÿ (êîíñòàíòû FILE_ACTION_XXX)
    FDrive       : String;  // Äèñê, íà êîòîðîì áûëî èçìåíåíèå
    FOldFileName : String;  // Èìÿ ôàéëà äî ïåðåèìåíîâàíèÿ
    FNewFileName : String;  // Èìÿ ôàéëà ïîñëå ïåðåèìåíîâàíèÿ
  end;

  // callback ïðîöåäóðà, âûçûâàåìàÿ ïðè èçìåíåíèè â ôàéëîâîé ñèñòåìå
  TWatchFileSystemCallBack = procedure (pInfo: TInfoCallBack);

  { Çàïóñê ìîíèòîðèíãà ôàéëîâîé ñèñòåìû
  Ïðàìåòðû:
  pName    - èìÿ ïàïêè äëÿ ìîíèòîðèíãà
  pFilter  - êîìáèíàöèÿ êîíñòàíò FILE_NOTIFY_XXX
  pSubTree - ìîíèòîðèòü ëè âñå ïîäïàïêè çàäàííîé ïàïêè
  pInfoCallBack - àäðåñ callback ïðîöåäóðû, âûçûâàåìîé ïðè èçìåíåíèè â ôàéëîâîé ñèñòåìå }
  procedure StartWatch(pName: String; pFilter: Cardinal; pSubTree: Boolean; pInfoCallBack: TWatchFileSystemCallBack);
  // Îñòàíîâêà ìîíèòîðèíãà
  procedure StopWatch;

implementation

uses
  Classes, Windows, SysUtils, IniFiles;

const
  FILE_LIST_DIRECTORY   = $0001;

type
  PFileNotifyInformation = ^TFileNotifyInformation;
  TFileNotifyInformation = record
    NextEntryOffset : DWORD;
    Action          : DWORD;
    FileNameLength  : DWORD;
    FileName        : Array[0..0] of WideChar;
  end;

  WFSError = class(Exception);

  TWFS = class(TThread)
  private
    FName           : String;
    FFilter         : Cardinal;
    FSubTree        : Boolean;
    FInfoCallBack   : TWatchFileSystemCallBack;
    FWatchHandle    : THandle;
    FWatchBuf       : Array[0..4096] of Byte;
    FOverLapp       : TOverlapped;
    FPOverLapp      : POverlapped;
    FBytesWritte    : DWORD;
    FCompletionPort : THandle;
    FNumBytes       : Cardinal;
    FOldFileName    : String;
    function CreateDirHandle(aDir: string): THandle;
    procedure WatchEvent;
    //procedure HandleEvent;
  protected
    procedure Execute; override;
  public
    constructor Create(pName: String; pFilter: Cardinal; pSubTree: Boolean; pInfoCallBack: TWatchFileSystemCallBack);
    destructor Destroy; override;
  end;


var
  WFS : TWFS;

procedure StartWatch(pName: String; pFilter: Cardinal; pSubTree: Boolean; pInfoCallBack: TWatchFileSystemCallBack);
begin
  WFS := TWFS.Create(pName, pFilter, pSubTree, pInfoCallBack);
end;

procedure StopWatch;
begin
  if Assigned(WFS) then
  begin
    PostQueuedCompletionStatus(WFS.FCompletionPort, 0, 0, nil);
    WFS.Terminate;
    WFS.WaitFor;
    WFS.Free;
    WFS := nil;
  end;
end;

constructor TWFS.Create(pName: String; pFilter: Cardinal; pSubTree: Boolean; pInfoCallBack: TWatchFileSystemCallBack);
begin
  inherited Create(True);
  FreeOnTerminate := False;
  FName := IncludeTrailingBackslash(pName);
  FFilter := pFilter;
  FSubTree := pSubTree;
  FOldFileName := EmptyStr;
  ZeroMemory(@FOverLapp, SizeOf(TOverLapped));
  FPOverLapp := @FOverLapp;
  ZeroMemory(@FWatchBuf, SizeOf(FWatchBuf));
  FInfoCallBack := pInfoCallBack;
  Resume;
end;


destructor TWFS.Destroy;
begin
  PostQueuedCompletionStatus(FCompletionPort, 0, 0, nil);
  CloseHandle(FWatchHandle);
  FWatchHandle := 0;
  CloseHandle(FCompletionPort);
  FCompletionPort := 0;
  inherited Destroy;
end;

function TWFS.CreateDirHandle(aDir: String): THandle;
begin
  Result := CreateFile(PChar(aDir), FILE_LIST_DIRECTORY, FILE_SHARE_READ+FILE_SHARE_DELETE+FILE_SHARE_WRITE,
                   nil,OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OVERLAPPED, 0);
end;

procedure TWFS.Execute;
begin
  FWatchHandle := CreateDirHandle(FName);
  WatchEvent;
end;

{procedure TWFS.HandleEvent;
var
  FileNotifyInfo : PFileNotifyInformation;
  InfoCallBack   : TInfoCallBack;
  Offset         : Longint;
begin
  Pointer(FileNotifyInfo) := @FWatchBuf[0];
  repeat
    Offset := FileNotifyInfo^.NextEntryOffset;
    InfoCallBack.FAction := FileNotifyInfo^.Action;
    InfoCallBack.FDrive := FName;
    SetString(InfoCallBack.FNewFileName,FileNotifyInfo^.FileName,FileNotifyInfo^.FileNameLength );
    InfoCallBack.FNewFileName := Trim(InfoCallBack.FNewFileName);
    case FileNotifyInfo^.Action of
      FILE_ACTION_RENAMED_OLD_NAME: FOldFileName := Trim(WideCharToString(@(FileNotifyInfo^.FileName[0])));
      FILE_ACTION_RENAMED_NEW_NAME: InfoCallBack.FOldFileName := FOldFileName;
    end;
    FInfoCallBack(InfoCallBack);
    PChar(FileNotifyInfo) := PChar(FileNotifyInfo)+Offset;
  until (Offset=0) or Terminated;
end;}

procedure TWFS.WatchEvent;
var
  {$ifdef DELPHIXE_UP}
  CompletionKey: DWORD_PTR;
  {$ELSE}
    CompletionKey: Cardinal;
  {$endif}
  // Ïåðåíåñåíî èç HandleEvent
  FileNotifyInfo : PFileNotifyInformation;
  InfoCallBack   : TInfoCallBack;
  Offset         : Longint;
  // End
begin
  FCompletionPort := CreateIoCompletionPort(FWatchHandle, 0, Longint(pointer(self)), 0);
  ZeroMemory(@FWatchBuf, SizeOf(FWatchBuf));
  if not ReadDirectoryChanges(FWatchHandle, @FWatchBuf, SizeOf(FWatchBuf), FSubTree,
    FFilter, @FBytesWritte,  @FOverLapp, 0) then
  begin
    raise WFSError.Create(SysErrorMessage(GetLastError));
    Terminate;
  end
  else
  begin
    while not Terminated do
    begin
      GetQueuedCompletionStatus(FCompletionPort, FNumBytes, CompletionKey, FPOverLapp, INFINITE);
      if CompletionKey <> 0 then
      begin
        //Synchronize(HandleEvent);
        { Ò.ê. Synchronize(HandleEvent) íå îòðàáàòûâàåò â
         ïëàãèíå ïî íåïîíÿòíîé ïðè÷èíå, òî åãî êîä ïåðåíåñåí ñþäà
         Ïîäðîáíåå òóò -> http://forum.qip.ru/showthread.php?t=25200 }
        Pointer(FileNotifyInfo) := @FWatchBuf[0];
        repeat
          Offset := FileNotifyInfo^.NextEntryOffset;
          InfoCallBack.FAction := FileNotifyInfo^.Action;
          InfoCallBack.FDrive := FName;
          SetString(InfoCallBack.FNewFileName,FileNotifyInfo^.FileName,FileNotifyInfo^.FileNameLength );
          InfoCallBack.FNewFileName := Trim(InfoCallBack.FNewFileName);
          case FileNotifyInfo^.Action of
            FILE_ACTION_RENAMED_OLD_NAME: FOldFileName := Trim(WideCharToString(@(FileNotifyInfo^.FileName[0])));
            FILE_ACTION_RENAMED_NEW_NAME: InfoCallBack.FOldFileName := FOldFileName;
          end;
          FInfoCallBack(InfoCallBack);
          PChar(FileNotifyInfo) := PChar(FileNotifyInfo)+Offset;
        until (Offset=0) or Terminated;
        // End synchronize
        ZeroMemory(@FWatchBuf, SizeOf(FWatchBuf));
        FBytesWritte := 0;
        ReadDirectoryChanges(FWatchHandle, @FWatchBuf, SizeOf(FWatchBuf), FSubTree, FFilter,
                             @FBytesWritte, @FOverLapp, 0);
      end
      else
        Terminate;
    end
  end
end;

end.