File: dirwatch.pp

package info (click to toggle)
fpc 3.2.2%2Bdfsg-49
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 341,452 kB
  • sloc: pascal: 3,820,194; xml: 194,356; ansic: 9,637; asm: 8,482; java: 5,346; sh: 4,813; yacc: 3,956; makefile: 2,705; lex: 2,661; javascript: 2,454; sql: 929; php: 474; cpp: 145; perl: 136; sed: 132; csh: 34; tcl: 7
file content (626 lines) | stat: -rw-r--r-- 13,549 bytes parent folder | download | duplicates (5)
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
unit dirwatch;
{$IFDEF LINUX}
{$DEFINE USEINOTIFY}
{$ELSE}
{$DEFINE USEGENERIC}
{$ENDIF}

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils,
{$IFDEF UNIX}
  baseunix,
{$IFDEF USEINOTIFY}
  ctypes,
  linux,
{$ENDIF}
{$ENDIF}
  contnrs;



Type
  TFileEvent = (feModify,feAttrib,feCreate,feDelete);
  TFileEvents = set of TFileEvent;

  { TDirectoryEntry }
  TDirectoryEntry = Class(TCollectionItem)
  private
    FEvents: TFileEvents;
    FName: String;
    FAttributes: Integer;
{$IFDEF UNIX}
    FGroup: gid_t;
    FMode: mode_t;
    FOwner: uid_t;
{$ENDIF}
    FSize: Int64;
    FTimeStamp: TDateTime;
  Protected
{$IFDEF USEGENERIC}
    procedure InitWatch(ABaseDir: String; AList: TFPStringHashTable);
{$ENDIF}
  Public
    Property TimeStamp : TDateTime Read FTimeStamp Write FTimeStamp;
    Property Size : Int64 Read FSize Write FSize;
    Property Attributes : Integer Read FAttributes Write FAttributes;
{$IFDEF UNIX}
    Property Mode : mode_t Read FMode Write FMode;
    Property Owner : uid_t Read FOwner Write FOwner;
    Property Group : gid_t Read FGroup Write FGroup;
{$ENDIF}
  Published
    Property Name : String Read FName Write FName;
    Property Events : TFileEvents Read FEvents Write FEvents;
  end;

  { TDirectoryEntries }

  TDirectoryEntries = Class(TCollection)
  private
    function GetE(AIndex : Integer): TDirectoryEntry;
    procedure SetE(AIndex : Integer; AValue: TDirectoryEntry);
  Public
    Function IndexOfEntry(Const AName : String) : Integer;
    Function EntryByName(Const AName : String) : TDirectoryEntry;
    Function AddEntry(Const AName : String) : TDirectoryEntry;
    Property Entries[AIndex : Integer] : TDirectoryEntry Read GetE Write SetE; default;
  end;

  TFileEventHandler = procedure (Sender : TObject; aEntry : TDirectoryEntry; AEvents : TFileEvents) of Object;

  { TDirwatch }

  TDirwatch = Class(TComponent)
  private
    FIdleInterval: Cardinal;
    FOnIdle: TNotifyEvent;
    FOnIdleNotify: TNotifyEvent;
    FTerminated: Boolean;
    FThreaded: Boolean;
    FWatches: TDirectoryEntries;
    FBaseDir: String;
    FOnChange: TFileEventHandler;
{$IFDEF USEGENERIC}
    FReference : TFPStringHashTable;
    FOldReference : TFPStringHashTable;
    procedure DoCheckItem(Item: String; const Key: string; var Continue: Boolean);
    procedure DoDeletedItem(Item: String; const Key: string; var Continue: Boolean);
{$ENDIF}
{$IFDEF USEINOTIFY}
    FINotifyFD : Cint;
{$ENDIF}
    function DirectoryEntryForFileName(S: String): TDirectoryEntry;
    procedure DoChangeEvent(Entry: TDirectoryEntry; Events: TFileEvents);
    procedure SetBaseDir(AValue: String);
  Protected
    procedure DoIdle; virtual;
    procedure Check; virtual;
    procedure DoneWatch; virtual;
    procedure DoStartWatch; virtual;
    procedure InitWatch;virtual;
  Public
    Constructor Create(AOWner : TComponent); override;
    Destructor Destroy; override;
    Procedure StartWatch;
    Procedure AddWatch(const aFileName : string; aEvents : TFileEvents);
    Procedure Terminate;
    Property Terminated : Boolean Read FTerminated;
  Published
    Property BaseDir : String read FBaseDir Write SetBaseDir;
    Property OnChange : TFileEventHandler Read FOnChange Write FOnChange;
    Property Threaded : Boolean Read FThreaded Write FThreaded;
    Property Watches : TDirectoryEntries Read FWatches Write FWatches;
    Property OnIdle : TNotifyEvent Read FOnIdle Write FOnIdleNotify;
    Property IdleInterval : Cardinal Read FIdleInterval Write FIdleInterval;
  end;

Const
  EventNames : Array[TFileEvent] of string = ('Modify','Attrib','Create','Delete');
  AllEvents =   [feModify,feAttrib,feCreate,feDelete];

Function FileEventsToStr(Events : TFileEvents) : String;

implementation


Function FileEventsToStr(Events : TFileEvents) : String;

Var
  E : TFileEvent;

begin
  Result:='';
  for E in Events do
    begin
    if Result<>'' then
      Result:=Result+',';
    Result:=Result+EventNames[E];
    end;

end;

{ TDirwatch }
Type

  { TDirwatchThread }

  TDirwatchThread = class(TThread)
  Private
    FDir:TDirWatch;
  Public
    Constructor Create(ADirwatch : TDirWatch);
    Procedure Execute; override;
  end;

{ TDirectoryEntry }

Function SearchRecToString(Info : TSearchRec; AEvents : TFileEvents) : String;

begin
  if feAttrib in AEvents then
    Result:=IntToStr(Info.Attr)
  else
    Result:='';
  Result:=Result+';'+IntToStr(Info.Size)+';'+IntToStr(Info.Time);
end;

{$IFDEF USEGENERIC}
procedure TDirectoryEntry.InitWatch(ABaseDir: String; AList: TFPStringHashTable);

Var
  Info : TSearchRec;
  FN : String;

begin
  if (ABaseDir<>'') then
    FN:=IncludeTrailingPathDelimiter(ABaseDir)+Name
  else
    FN:=Name;
  if FindFirst(FN,faAnyFile,Info)=0 then
    begin
    if (faDirectory and Info.Attr) = 0 then
      begin
      AList.Add(FN,SearchRecToString(Info,Self.Events))
      end
    else
      begin
      FindClose(Info);
      FN:=IncludeTrailingPathDelimiter(FN);
      if FindFirst(FN+AllFilesMask,0,Info)=0  then
        Repeat
          if (info.Name<>'.') and (Info.Name<>'..') then
            AList.Add(FN+Info.Name,SearchRecToString(Info,Self.Events));
        until (FindNext(Info)<>0)
      end;
    FindClose(Info);
    end
end;

{$ENDIF}
{$IFDEF USEINOTIFY}

{$ENDIF}
{ TDirwatchThread }

constructor TDirwatchThread.Create(ADirwatch: TDirWatch);

begin
  FDir:=ADirWatch;
  FreeOnTerminate:=True;
  inherited create(False);
end;

procedure TDirwatchThread.Execute;
begin
  FDir.DoStartWatch;
end;


procedure TDirwatch.SetBaseDir(AValue: String);
begin
  if FBaseDir=AValue then Exit;
  FBaseDir:=AValue;
  FWatches.Clear;
end;

constructor TDirwatch.Create(AOWner: TComponent);
begin
  inherited Create(AOWner);
  FWatches:=TDirectoryEntries.Create(TDirectoryEntry);
  FidleInterval:=100;
end;

destructor TDirwatch.Destroy;
begin
  FreeAndNil(FWatches);
  inherited Destroy;
end;

Type
  { TDirwatchChange }
  TDirwatchChange = Class
    FEntry : TDirectoryEntry;
    FEvents : TFileEvents;
    FDirWatch : TDirWatch;
    Constructor Create(AEntry : TDirectoryEntry;aEvents : TFileEvents;ADirWatch : TDirWatch);
    Procedure DoEvent;
 end;

{ TDirwatchChange }

constructor TDirwatchChange.Create(AEntry: TDirectoryEntry; aEvents: TFileEvents; ADirWatch: TDirWatch);

begin
  FEntry:=AEntry;
  FEvents:=AEvents;
  FDirWatch:=ADirWatch;
end;

procedure TDirwatchChange.DoEvent;
begin
  FDirwatch.FonChange(FDirwatch,FEntry,FEvents);
end;

Procedure TDirwatch.DoChangeEvent(Entry : TDirectoryEntry; Events : TFileEvents);

Var
  W : TDirWatchChange;

begin
  try
    if Assigned(FOnChange) then
      if Not Threaded then
        FonChange(Self,Entry,Events)
      else
        begin
        W:=TDirWatchChange.Create(Entry,Events,Self);
        try
          TThread.Synchronize(TThread.CurrentThread,@W.DoEvent)
        finally
          W.Free;
        end;
        end
  Finally
    // Specially created
    if Entry.Collection=Nil then
      FreeAndNil(Entry);
  end;
end;


procedure TDirwatch.DoIdle;

begin
  if Assigned(FOnIdle) then
    FOnIdle(Self);
end;

Function TDirwatch.DirectoryEntryForFileName(S : String) : TDirectoryEntry;

begin
  Result:=FWatches.EntryByName(S);
  if (Result=Nil) then
    Result:=FWatches.EntryByName(ExtractFilePath(S));
  if (Result=Nil) then
    begin
    Result:=TDirectoryEntry.Create(Nil);
    Result.Name:=S;
    end;
end;

{$IFDEF USEGENERIC}
procedure TDirwatch.DoneWatch;

begin
  FreeAndNil(FReference);
end;

procedure TDirwatch.InitWatch;

Var
  I : Integer;

begin
  FReference:=TFPStringHashTable.Create;
  For I:=0 to FWatches.Count-1 do
    FWatches[i].InitWatch(BaseDir,FReference);
end;

procedure TDirwatch.DoDeletedItem(Item: String; const Key: string; var Continue: Boolean);

Var
  DE : TDirectoryEntry;

begin
  DE:=FWatches.EntryByName(Key);
  if (DE=Nil) then
    DE:=FWatches.EntryByName(ExtractFilePath(Key));
  if (DE=Nil) then
    begin
    DE:=TDirectoryEntry.Create(Nil);
    DE.Name:=Key;
    end;
  DoChangeEvent(DE,[feDelete]);
  Continue:=False;
end;

procedure TDirwatch.DoCheckItem(Item: String; const Key: string; var Continue: Boolean);

Var
  S : String;
  E : TFileEvents;
  DE : TDirectoryEntry;

begin
//  Writeln('check file: ',key,' attrs : ',Item);
  E:=[];
  S:=FOldReference[Key];
  if (S='') then
    E:=[feCreate]
  else
    begin
    FOldReference.Delete(Key);
    if (S<>Item) then
      E:=[feAttrib];
    end;
  if E<>[] then
    begin
    DE:=DirectoryEntryForFileName(Key);
    DoChangeEvent(DE,E);
    Continue:=False;
    end;
end;

procedure TDirwatch.Check;

begin
  FOldReference:=FReference;
  try
    FReference:=TFPStringHashTable.Create;
    InitWatch;
    FReference.Iterate(@doCheckItem);
    if FoldReference.Count>0 then
      FReference.Iterate(@doDeletedItem);
      // Deleted files
    Sleep(IdleInterval);
  finally
    FreeAndNil(FoldReference);
  end;
end;
{$ENDIF}

{$IFDEF USEINOTIFY}
Procedure WatchDirectory(d : string);

Const
  Events = IN_MODIFY or IN_ATTRIB or IN_CREATE or IN_DELETE;

Var
  fd, wd,fnl,len : cint;
  fds : tfdset;
  e : ^inotify_event;
  buf : Array[0..1023*4] of Byte; // 4K Buffer
  fn : string;
  p : pchar;

begin
  fd:=inotify_init;
  try
    wd:=inotify_add_watch(fd,pchar(d),Events);
    fpFD_Zero(fds);
    fpFD_SET(fd,fds);
    While (fpSelect(fd+1,@fds,nil,nil,nil)>=0) do
      begin
      len:=fpRead(fd,buf,sizeof(buf));
      e:=@buf;
      While ((pchar(e)-@buf)<len) do
        begin
        fnl:=e^.len;
        if (fnl>0) then
          begin
          p:=@e^.name+fnl-1;
          While (p^=#0) do
            begin
            dec(p);
            dec(fnl);
            end;
          end;
        setlength(fn,fnl);
        if (fnl>0) then
          move(e^.name,fn[1],fnl);
        {$ifdef VerboseDirWatch}
        Writeln('Change ',e^.mask,' (',
//                InotifyEventsToString(e^.mask),
                ') detected for file "',fn,'"');
        {$endif}
        ptrint(e):=ptrint(e)+sizeof(inotify_event)+e^.len-1;
        end;
      end;
  finally
    fpClose(fd);
  end;
end;

procedure TDirwatch.DoneWatch;

begin
  fpClose(FInotifyFD);
end;

procedure TDirwatch.InitWatch;

Const
  NativeEvents : Array[TFileEvent] of cint = (IN_Modify,IN_Attrib,IN_Create,IN_Delete);

Var
  WD,I,NEvents : Integer;
  E : TFileEvent;
  BD,FN : String;

begin
  BD:=BaseDir;
  if BD<>'' then
    BD:=IncludeTrailingPathDelimiter(BD);
  FINotifyFD:=inotify_init;
  For I:=0 to FWatches.Count-1 do
    begin
    NEvents:=0;
    for E in FWatches[i].Events do
      NEvents:=NEvents OR NativeEvents[E];
    FN:=BD+FWatches[i].Name;
    wd:=inotify_add_watch(FINotifyFD,PChar(FN),NEvents);
    end;
end;

Function NativeEventsToEvents(Native : cint) : TFileEvents;

  Procedure MA(C : cint; AEvent : TFileEvent);

  begin
    if (Native and C)<>0 then
      Include(Result,AEvent);
  end;

begin
  Result:=[];
  MA(IN_ACCESS,feAttrib);
  MA(IN_MODIFY,feModify);
  MA(IN_ATTRIB,feAttrib);
  MA(IN_CLOSE_WRITE,feAttrib);
  MA(IN_CLOSE_NOWRITE,feAttrib);
  MA(IN_OPEN,feAttrib);
  MA(IN_MOVED_FROM,feCreate);
  MA(IN_MOVED_TO,feDelete);
  MA(IN_CREATE,feCreate);
  Ma(IN_DELETE,feDelete);
  Ma(IN_DELETE_SELF,feDelete);
  Ma(IN_MOVE_SELF,feDelete);
  Ma(IN_UNMOUNT,feDelete);
  // IN_Q_OVERFLOW
  // IN_IGNORED

end;

procedure TDirwatch.Check;

Var
  fnl,len : cint;
  e : ^inotify_event;
  buf : Array[0..1023*4] of Byte; // 4K Buffer
  fn : string;
  p : pchar;
  fds : tfdset;
  Timeout : ttimeval;

begin
  fpFD_Zero(fds);
  fpFD_SET(FINotifyFD,fds);
  timeout.tv_sec:=FIdleInterval div 1000;
  timeout.tv_usec:=(FIdleInterval mod 1000)*1000;
  if (fpSelect(FINotifyFD+1,@fds,nil,nil,@Timeout)<=0) then
    exit;
  len:=fpRead(FINotifyFD,buf,sizeof(buf));
  e:=@buf;
  While ((pchar(e)-@buf)<len) do
    begin
    fnl:=e^.len;
    if (fnl>0) then
      begin
      p:=@e^.name+fnl-1;
      While (p^=#0) do
        begin
        dec(p);
        dec(fnl);
        end;
      end;
    setlength(fn,fnl);
    if (fnl>0) then
      move(e^.name,fn[1],fnl);
    DoChangeEvent(DirectoryEntryForFileName(FN),NativeEventsToEvents(E^ .mask));
    ptrint(e):=ptrint(e)+sizeof(inotify_event)+e^.len-1;
    end;
end;
{$ENDIF}

procedure TDirwatch.DoStartWatch;

begin
  InitWatch;
  try
    While not Terminated do
      begin
      Check;
      if Threaded then
        TThread.Synchronize(TThread.CurrentThread,@DoIdle)
      else
        DoIdle;
      end;
  Finally
    DoneWatch;
  end;
end;

procedure TDirwatch.StartWatch;

begin
  If Threaded then
    TDirwatchThread.Create(Self).WaitFor
  else
    DoStartWatch;
end;

procedure TDirwatch.AddWatch(const aFileName: string; aEvents: TFileEvents);
begin
  FWatches.AddEntry(AFileName).Events:=AEvents;
end;

procedure TDirwatch.Terminate;
begin
  FTerminated:=True;
end;

{ TDirectoryEntries }

function TDirectoryEntries.GetE(AIndex : Integer): TDirectoryEntry;
begin
  Result:=TDirectoryEntry(Items[AIndex]);
end;

procedure TDirectoryEntries.SetE(AIndex : Integer; AValue: TDirectoryEntry);
begin
  Items[AIndex]:=AValue;
end;

function TDirectoryEntries.IndexOfEntry(const AName: String): Integer;

begin
  Result:=Count-1;
  While (Result>=0) and (GetE(Result).Name<>AName) do
    Dec(Result);
end;

function TDirectoryEntries.EntryByName(const AName: String): TDirectoryEntry;

Var
  I : Integer;

begin
  I:=IndexOfEntry(AName);
  If (I=-1) then
    Result:=Nil
  else
    Result:=GetE(I);
end;

function TDirectoryEntries.AddEntry(Const AName: String): TDirectoryEntry;
begin
  Result:=Add as TDirectoryEntry;
  Result.Name:=AName;
end;

end.