Monitor.vala
[gitlive] / Monitor.vala
1 //<Script type="text/javascript">
2 //var Gio     = imports.gi.Gio;
3 //var GLib    = imports.gi.GLib;
4
5 //var XObject = imports.XObject.XObject;
6 //var File    = imports.File.File;
7
8 /// # valac  --pkg gio-2.0  --pkg posix Monitor.vala -o /tmp/Monitor
9
10  
11 //using Gee; // for array list?
12 /*
13 static int main (string[] args) {
14     // A reference to our file
15     //var file = File.new_for_path ("data.txt");
16     MainLoop loop = new MainLoop ();
17     print("starting");
18     var m = new Monitor();
19     
20     m.add("/home/alan/gitlive");
21     m.start();
22     loop.run ();
23
24     return 0;
25
26 }
27 */
28
29 public class  MonitorNamePathDir {
30     public string action;
31     public string name;
32     public string path;
33     public string dir;
34     
35     public MonitorNamePathDir(string name, string path, string dir)
36     {
37         this.name = name;
38         this.path = path;
39         this.dir = dir;
40         this.action = "?";
41         
42     }
43 }
44
45
46
47 public delegate void onEventHander (FileMonitor fm, File f_orig, File of_orig, FileMonitorEvent event_type);
48
49
50 /**
51  * Monitor class - handles monitor managment for a large tree...
52  *
53  *
54  * This 
55  * 
56  * usage : 
57  * x = new Monitor({
58      change : function () {
59          * ....
60          *}
61   }
62  * x.add('/somepath')
63  * x.stop() // stops all scanning.
64  * x.play(); // starts the scanning
65  * 
66  * 
67  * 
68  * 
69  */
70  
71 public class Monitor : Object
72 {
73
74
75
76     public Monitor()
77     {
78        
79      
80         this.monitors = new Array<FileMonitor> ();
81         this.top = new Array<string> ();
82         this.paused = false;
83     }
84      
85     public Array<FileMonitor> monitors;// Array of MonitorNamePathDirileMonitors
86     public Array<string> top; // list of top level directories..
87     public bool paused;
88     /**
89      * add a directory or file to monitor
90      */
91     public void add (string add)
92     {
93         
94         print("Monitor.add: " + add);
95         this.top.append_val(add);
96     }
97     /**
98      * start monitoring
99      */
100     public void start()
101     {
102         for(int i = 0; i < this.top.length ; i++) {
103             this.monitor(this.top.index(i));
104         }
105     }
106     /**
107      * stop / pause monitoring
108      * 
109      */
110     public void stop()
111     {
112         
113         for(int i = 0; i < this.monitors.length ; i++) {
114             this.monitors.index(i).cancel();
115         } 
116         this.monitors = new Array<FileMonitor>(); // clean /destroy/ kill old?
117     }
118     /**
119      * pause monitoring - without changing what's monitored 
120      */
121     public void pause()
122     {
123         this.paused = true;
124     }
125     /**
126      * resume monitoring - without changing what's monitored 
127      */
128     public void resume()
129     {
130         this.paused = false;
131     }
132     /**
133      * monitor a file or directory (privatish)
134      *
135      * initially called with ~/gitlive  null 0 (effectvely)
136      * 
137      * 
138      */
139     public void monitor(string path, int depth = 0)
140     {
141          
142         //GLib.debug("ADD: (%d): %s\n", depth, path);
143         
144         //depth = typeof(depth) == 'number'  ? depth *1 : 0;
145         depth = depth > 0  ? depth *1 : 0;
146         
147         
148         //fn = fn || function (fm, f, of, event_type, uh) {
149         //    _this.onEvent(fm, f, of, event_type, uh);
150         //}
151                  
152         var f = File.new_for_path(path);
153             //var cancel = new Gio.Cancellable ();
154         if (depth > 0) { 
155   
156             try {
157                  var fm = f.monitor(FileMonitorFlags.SEND_MOVED + FileMonitorFlags.WATCH_MOVES,null);  
158                  //var fm = f.monitor(FileMonitorFlags.WATCH_MOVES,null);
159  
160                  fm.changed.connect( this.onEvent );
161                 this.monitors.append_val(fm);
162
163             } catch (Error e) {
164                   GLib.debug("Error adding monitor: %s", e.message);
165                 // FIXME -- show error? do nothing..            
166             }
167             // print("ADD path " + depth + ' ' + path);
168         }
169         // iterate children?
170         // - this is not used.
171         //if (GLib.file_test(path + '/.git' , GLib.FileTest.IS_DIR) && this.initRepo) {
172             
173         //    this.initRepo(path);
174         //}
175         FileEnumerator file_enum;
176         var cancellable = new Cancellable ();
177         try {      
178             file_enum = f.enumerate_children(
179                FileAttribute.STANDARD_DISPLAY_NAME + "," +   FileAttribute.STANDARD_TYPE,
180                         FileQueryInfoFlags.NOFOLLOW_SYMLINKS,  // FileQueryInfoFlags.NONE,
181                cancellable);
182         } catch (Error e) {
183             // FIXME - show error..
184             return;
185         }
186         FileInfo next_file;
187         
188         while (cancellable.is_cancelled () == false ) {
189             try {
190                 next_file = file_enum .next_file (cancellable);
191             } catch(Error e) {
192                 print(e.message);
193                 break;
194             }
195
196             if (next_file == null) {
197                 break;
198             }
199
200             //print("got a file " + next_file.sudo () + '?=' + Gio.FileType.DIRECTORY);
201
202             if (next_file.get_file_type() != FileType.DIRECTORY) {
203                 next_file = null;
204                 continue;
205             }
206
207
208             //stdout.printf("Monitor.monitor: got file %s : type :%u\n",
209             //        next_file.get_display_name(), next_file.get_file_type());
210
211
212             if (next_file.get_is_symlink()) {
213                 next_file = null;
214                 continue;
215             }
216             
217             if (next_file.get_display_name()[0] == '.') {
218                 next_file = null;
219                 continue;
220             }
221             var sp = path+"/"+next_file.get_display_name();
222             // skip modules.
223             //print("got a file : " + sp);
224          
225             next_file = null;
226             
227             
228             
229             this.monitor(sp, depth + 1);
230             
231         }
232         try {
233             file_enum.close(null);
234         } catch(Error e) {
235             // ignore?
236         }
237     }
238     
239     
240     
241     public File realpath(File file)
242     {
243         if (file != null) {
244             return file;
245         }
246         
247         if (FileUtils.test(file.get_path(), FileTest.EXISTS)) {
248             var rp = Posix.realpath(file.get_path());
249             return File.new_for_path(rp);  
250             
251         }
252         // file does not currently exist..
253         // check parent.
254         
255 // FIX ME - string split?/? 
256         var bn = file.get_basename();
257         var ar =  file.get_path().split("/");
258         ar.resize(ar.length-1);
259         var dirname = string.joinv("/",ar );
260         var rp = Posix.realpath(dirname);
261         return File.new_for_path(rp + "/" + bn);
262         
263     }
264    
265     
266     
267      
268     public void onEvent(File f_orig, File? of_orig, FileMonitorEvent event_type)
269     {
270         if (this.paused) {
271             return;
272         }
273        // print("onEvent\n");
274         var f = this.realpath(f_orig);
275         
276  
277         MonitorNamePathDir src = new MonitorNamePathDir( f.get_basename(), f.get_path() , Path.get_dirname(f.get_path()));
278  
279         
280        
281         //string event_name = "UKNOWN";
282         
283         
284         // extract the event names ... - not sure if introspection is feasible in vala..
285         //for(var i in Gio.FileMonitorEvent) {
286          //    if (Gio.FileMonitorEvent[i] == event_type) {
287          //        event_name = i;
288          //    }
289          //}
290         
291
292
293
294         //print (JSON.stringify([event_name , f.get_path(), of ? of.get_path() : false ] ));
295         //print ("got src: " + src.toString());
296         //print ("got event: " + src.toString());
297         try {
298                 
299
300             switch(event_type) {
301                 case FileMonitorEvent.CHANGED:
302                     src.action = "changed";
303                     this.onChanged(src);
304                     return; // ingore thise?? -wait for changes_done_htin?
305                     
306                 case FileMonitorEvent.CHANGES_DONE_HINT:
307                     src.action = "changed";
308                     this.onChangesDoneHint(src);
309                     return;
310                     
311                 case FileMonitorEvent.DELETED:
312                     src.action = "rm";
313                     this.onDeleted(src);
314                     return;
315                     
316                 case FileMonitorEvent.CREATED:
317                     src.action = "created";
318                     this.onCreated(src);
319                     return;
320                 
321                 case FileMonitorEvent.ATTRIBUTE_CHANGED: // eg. chmod/chatt
322                     src.action = "attrib";
323                     this.onAttributeChanged(src);
324                     return;
325                 
326                 case FileMonitorEvent.MOVED: // eg. chmod/chatt
327                 case FileMonitorEvent.MOVED_IN: // eg. chmod/chatt
328                 case FileMonitorEvent.MOVED_OUT: // eg. chmod/chatt                                
329                 case FileMonitorEvent.RENAMED: // eg. chmod/chatt                      
330
331                       var of = this.realpath(of_orig);
332                        var   dest = new MonitorNamePathDir(
333                                      of.get_basename(), 
334                                     of.get_path(),  
335                                     Path.get_dirname(of.get_path())
336                                 );
337
338                     src.action = "moved";
339                     dest.action = "moved";
340                     this.onMoved(src,dest);
341                     return; 
342                     
343  
344                 default:
345                     stdout.printf("event type not handled %u", event_type);
346                     break;
347                 // rest are mount related - not really relivant.. maybe add later..
348             } 
349         } catch(Error e) {
350             print(e.message);
351         }
352         
353     }
354     
355
356     /** override these to do stuff.. */
357     //public void initRepo(MonitorNamePathDir src) { } // called on startup at the top level repo dir.
358     public virtual void  onChanged(MonitorNamePathDir src) { }
359     public virtual void onChangesDoneHint(MonitorNamePathDir src) { }
360     public virtual void onDeleted(MonitorNamePathDir src) { }
361     public virtual void onCreated(MonitorNamePathDir src) { }
362     public virtual void onAttributeChanged(MonitorNamePathDir src) { }
363     public virtual void onMoved(MonitorNamePathDir src,MonitorNamePathDir dest) { }
364           
365     
366 }
367  
368  
369
370
371
372
373