Merge branch 'tree-refcount'
[platform/upstream/glib.git] / gio / gfilemonitor.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24 #include <string.h>
25
26 #include "gfilemonitor.h"
27 #include "gio-marshal.h"
28 #include "gioenumtypes.h"
29 #include "gfile.h"
30 #include "gvfs.h"
31 #include "glibintl.h"
32
33 #include "gioalias.h"
34
35 struct _FileChange;
36 typedef struct _FileChange FileChange;
37 static void file_change_free (FileChange *change);
38
39 /**
40  * SECTION:gfilemonitor
41  * @short_description: File Monitor
42  * @include: gio/gio.h
43  *
44  * Monitors a file or directory for changes.
45  *
46  * To obtain a #GFileMonitor for a file or directory, use
47  * g_file_monitor(), g_file_monitor_file(), or
48  * g_file_monitor_directory().
49  *
50  * To get informed about changes to the file or directory you are
51  * monitoring, connect to the #GFileMonitor::changed signal. The
52  * signal will be emitted in the <link
53  * linkend="g-main-context-push-thread-default">thread-default main
54  * context</link> of the thread that the monitor was created in
55  * (though if the global default main context is blocked, this may
56  * cause notifications to be blocked even if the thread-default
57  * context is still running).
58  **/
59
60 G_LOCK_DEFINE_STATIC(cancelled);
61
62 enum {
63   CHANGED,
64   LAST_SIGNAL
65 };
66
67 /* work around a limitation of the aliasing foo */
68 #undef g_file_monitor
69
70 G_DEFINE_ABSTRACT_TYPE (GFileMonitor, g_file_monitor, G_TYPE_OBJECT);
71
72 typedef struct {
73   GFile *file;
74   guint32 last_sent_change_time; /* 0 == not sent */
75   guint32 send_delayed_change_at; /* 0 == never */
76   guint32 send_virtual_changes_done_at; /* 0 == never */
77 } RateLimiter;
78
79 struct _GFileMonitorPrivate {
80   gboolean cancelled;
81   int rate_limit_msec;
82
83   /* Rate limiting change events */
84   GHashTable *rate_limiter;
85
86   GSource *pending_file_change_source;
87   GSList *pending_file_changes; /* FileChange */
88
89   GSource *timeout;
90   guint32 timeout_fires_at;
91
92   GMainContext *context;
93 };
94
95 enum {
96   PROP_0,
97   PROP_RATE_LIMIT,
98   PROP_CANCELLED
99 };
100
101 static void
102 g_file_monitor_set_property (GObject      *object,
103                              guint         prop_id,
104                              const GValue *value,
105                              GParamSpec   *pspec)
106 {
107   GFileMonitor *monitor;
108
109   monitor = G_FILE_MONITOR (object);
110
111   switch (prop_id)
112     {
113     case PROP_RATE_LIMIT:
114       g_file_monitor_set_rate_limit (monitor, g_value_get_int (value));
115       break;
116
117     default:
118       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
119       break;
120     }
121 }
122
123 static void
124 g_file_monitor_get_property (GObject    *object,
125                              guint       prop_id,
126                              GValue     *value,
127                              GParamSpec *pspec)
128 {
129   GFileMonitor *monitor;
130   GFileMonitorPrivate *priv;
131
132   monitor = G_FILE_MONITOR (object);
133   priv = monitor->priv;
134
135   switch (prop_id)
136     {
137     case PROP_RATE_LIMIT:
138       g_value_set_int (value, priv->rate_limit_msec);
139       break;
140
141     case PROP_CANCELLED:
142       G_LOCK (cancelled);
143       g_value_set_boolean (value, priv->cancelled);
144       G_UNLOCK (cancelled);
145       break;
146
147     default:
148       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
149       break;
150     }
151 }
152
153 #define DEFAULT_RATE_LIMIT_MSECS 800
154 #define DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS 2
155
156 static guint signals[LAST_SIGNAL] = { 0 };
157
158 static void
159 rate_limiter_free (RateLimiter *limiter)
160 {
161   g_object_unref (limiter->file);
162   g_slice_free (RateLimiter, limiter);
163 }
164
165 static void
166 g_file_monitor_finalize (GObject *object)
167 {
168   GFileMonitor *monitor;
169
170   monitor = G_FILE_MONITOR (object);
171
172   if (monitor->priv->timeout)
173     {
174       g_source_destroy (monitor->priv->timeout);
175       g_source_unref (monitor->priv->timeout);
176     }
177
178   g_hash_table_destroy (monitor->priv->rate_limiter);
179
180   if (monitor->priv->context)
181     g_main_context_unref (monitor->priv->context);
182
183   G_OBJECT_CLASS (g_file_monitor_parent_class)->finalize (object);
184 }
185
186 static void
187 g_file_monitor_dispose (GObject *object)
188 {
189   GFileMonitor *monitor;
190   GFileMonitorPrivate *priv;
191   
192   monitor = G_FILE_MONITOR (object);
193   priv = monitor->priv;
194
195   if (priv->pending_file_change_source)
196     {
197       g_source_destroy (priv->pending_file_change_source);
198       g_source_unref (priv->pending_file_change_source);
199       priv->pending_file_change_source = NULL;
200     }
201   g_slist_foreach (priv->pending_file_changes, (GFunc) file_change_free, NULL);
202   g_slist_free (priv->pending_file_changes);
203   priv->pending_file_changes = NULL;
204
205   /* Make sure we cancel on last unref */
206   g_file_monitor_cancel (monitor);
207
208   G_OBJECT_CLASS (g_file_monitor_parent_class)->dispose (object);
209 }
210
211 static void
212 g_file_monitor_class_init (GFileMonitorClass *klass)
213 {
214   GObjectClass *object_class;
215   
216   g_type_class_add_private (klass, sizeof (GFileMonitorPrivate));
217   
218   object_class = G_OBJECT_CLASS (klass);
219   object_class->finalize = g_file_monitor_finalize;
220   object_class->dispose = g_file_monitor_dispose;
221   object_class->get_property = g_file_monitor_get_property;
222   object_class->set_property = g_file_monitor_set_property;
223
224   /**
225    * GFileMonitor::changed:
226    * @monitor: a #GFileMonitor.
227    * @file: a #GFile.
228    * @other_file: a #GFile.
229    * @event_type: a #GFileMonitorEvent.
230    * 
231    * Emitted when a file has been changed. 
232    **/
233   signals[CHANGED] =
234     g_signal_new (I_("changed"),
235                   G_TYPE_FILE_MONITOR,
236                   G_SIGNAL_RUN_LAST,
237                   G_STRUCT_OFFSET (GFileMonitorClass, changed),
238                   NULL, NULL,
239                   _gio_marshal_VOID__OBJECT_OBJECT_ENUM,
240                   G_TYPE_NONE, 3,
241                   G_TYPE_FILE, G_TYPE_FILE, G_TYPE_FILE_MONITOR_EVENT);
242
243   g_object_class_install_property (object_class,
244                                    PROP_RATE_LIMIT,
245                                    g_param_spec_int ("rate-limit",
246                                                      P_("Rate limit"),
247                                                      P_("The limit of the monitor to watch for changes, in milliseconds"),
248                                                      0, G_MAXINT,
249                                                      DEFAULT_RATE_LIMIT_MSECS,
250                                                      G_PARAM_READWRITE|
251                                                      G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
252
253   g_object_class_install_property (object_class,
254                                    PROP_CANCELLED,
255                                    g_param_spec_boolean ("cancelled",
256                                                          P_("Cancelled"),
257                                                          P_("Whether the monitor has been cancelled"),
258                                                          FALSE,
259                                                          G_PARAM_READABLE|
260                                                          G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
261 }
262
263 static void
264 g_file_monitor_init (GFileMonitor *monitor)
265 {
266   monitor->priv = G_TYPE_INSTANCE_GET_PRIVATE (monitor,
267                                                G_TYPE_FILE_MONITOR,
268                                                GFileMonitorPrivate);
269   monitor->priv->rate_limit_msec = DEFAULT_RATE_LIMIT_MSECS;
270   monitor->priv->rate_limiter = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal,
271                                                        NULL, (GDestroyNotify) rate_limiter_free);
272   monitor->priv->context = g_main_context_get_thread_default ();
273 }
274
275 /**
276  * g_file_monitor_is_cancelled:
277  * @monitor: a #GFileMonitor
278  * 
279  * Returns whether the monitor is canceled.
280  *
281  * Returns: %TRUE if monitor is canceled. %FALSE otherwise.
282  **/
283 gboolean
284 g_file_monitor_is_cancelled (GFileMonitor *monitor)
285 {
286   gboolean res;
287
288   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
289
290   G_LOCK (cancelled);
291   res = monitor->priv->cancelled;
292   G_UNLOCK (cancelled);
293   
294   return res;
295 }
296
297 /**
298  * g_file_monitor_cancel:
299  * @monitor: a #GFileMonitor.
300  * 
301  * Cancels a file monitor.
302  * 
303  * Returns: %TRUE if monitor was cancelled.
304  **/
305 gboolean
306 g_file_monitor_cancel (GFileMonitor* monitor)
307 {
308   GFileMonitorClass *klass;
309   
310   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
311   
312   G_LOCK (cancelled);
313   if (monitor->priv->cancelled)
314     {
315       G_UNLOCK (cancelled);
316       return TRUE;
317     }
318   
319   monitor->priv->cancelled = TRUE;
320   G_UNLOCK (cancelled);
321   
322   g_object_notify (G_OBJECT (monitor), "cancelled");
323
324   klass = G_FILE_MONITOR_GET_CLASS (monitor);
325   return (* klass->cancel) (monitor);
326 }
327
328 /**
329  * g_file_monitor_set_rate_limit:
330  * @monitor: a #GFileMonitor.
331  * @limit_msecs: a integer with the limit in milliseconds to 
332  * poll for changes.
333  *
334  * Sets the rate limit to which the @monitor will report
335  * consecutive change events to the same file. 
336  * 
337  **/
338 void
339 g_file_monitor_set_rate_limit (GFileMonitor *monitor,
340                                int           limit_msecs)
341 {
342   GFileMonitorPrivate *priv;
343   
344   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
345   
346   priv = monitor->priv;
347   if (priv->rate_limit_msec != limit_msecs)
348     {
349       monitor->priv->rate_limit_msec = limit_msecs;
350       g_object_notify (G_OBJECT (monitor), "rate-limit");
351     }
352 }
353
354 struct _FileChange {
355   GFile             *child;
356   GFile             *other_file;
357   GFileMonitorEvent  event_type;
358 };
359
360 static void
361 file_change_free (FileChange *change)
362 {
363   g_object_unref (change->child);
364   if (change->other_file)
365     g_object_unref (change->other_file);
366   
367   g_slice_free (FileChange, change);
368 }
369
370 static gboolean
371 emit_cb (gpointer data)
372 {
373   GFileMonitor *monitor = G_FILE_MONITOR (data);
374   GSList *pending, *iter;
375   
376   pending = g_slist_reverse (monitor->priv->pending_file_changes);
377   monitor->priv->pending_file_changes = NULL;
378   if (monitor->priv->pending_file_change_source)
379     {
380       g_source_unref (monitor->priv->pending_file_change_source);
381       monitor->priv->pending_file_change_source = NULL;
382     }
383
384   g_object_ref (monitor);
385   for (iter = pending; iter; iter = iter->next)
386     {
387        FileChange *change = iter->data;
388        g_signal_emit (monitor, signals[CHANGED], 0,
389                       change->child, change->other_file, change->event_type);
390        file_change_free (change);
391     }
392   g_slist_free (pending);
393   g_object_unref (monitor);
394
395   return FALSE;
396 }
397
398 static void
399 emit_in_idle (GFileMonitor      *monitor,
400               GFile             *child,
401               GFile             *other_file,
402               GFileMonitorEvent  event_type)
403 {
404   GSource *source;
405   FileChange *change;
406   GFileMonitorPrivate *priv;
407
408   priv = monitor->priv;
409
410   change = g_slice_new (FileChange);
411
412   change->child = g_object_ref (child);
413   if (other_file)
414     change->other_file = g_object_ref (other_file);
415   else
416     change->other_file = NULL;
417   change->event_type = event_type;
418
419   if (!priv->pending_file_change_source)
420     {
421       source = g_idle_source_new ();
422       priv->pending_file_change_source = source;
423       g_source_set_priority (source, 0);
424
425       /* We don't ref monitor here - instead dispose will free any
426        * pending idles.
427        */
428       g_source_set_callback (source, emit_cb, monitor, NULL);
429       g_source_attach (source, monitor->priv->context);
430     }
431   /* We reverse this in the processor */
432   priv->pending_file_changes = g_slist_prepend (priv->pending_file_changes, change);
433 }
434
435 static guint32
436 get_time_msecs (void)
437 {
438   return g_thread_gettime() / (1000 * 1000);
439 }
440
441 static guint32
442 time_difference (guint32 from, guint32 to)
443 {
444   if (from > to)
445     return 0;
446   return to - from;
447 }
448
449 /* Change event rate limiting support: */
450
451 static RateLimiter *
452 new_limiter (GFileMonitor *monitor,
453              GFile             *file)
454 {
455   RateLimiter *limiter;
456
457   limiter = g_slice_new0 (RateLimiter);
458   limiter->file = g_object_ref (file);
459   g_hash_table_insert (monitor->priv->rate_limiter, file, limiter);
460   
461   return limiter;
462 }
463
464 static void
465 rate_limiter_send_virtual_changes_done_now (GFileMonitor *monitor, 
466                                             RateLimiter  *limiter)
467 {
468   if (limiter->send_virtual_changes_done_at != 0)
469     {
470       emit_in_idle (monitor, limiter->file, NULL,
471                     G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT);
472       limiter->send_virtual_changes_done_at = 0;
473     }
474 }
475
476 static void
477 rate_limiter_send_delayed_change_now (GFileMonitor *monitor, 
478                                       RateLimiter *limiter, 
479                                       guint32 time_now)
480 {
481   if (limiter->send_delayed_change_at != 0)
482     {
483       emit_in_idle (monitor, 
484                     limiter->file, NULL,
485                     G_FILE_MONITOR_EVENT_CHANGED);
486       limiter->send_delayed_change_at = 0;
487       limiter->last_sent_change_time = time_now;
488     }
489 }
490
491 typedef struct {
492   guint32 min_time;
493   guint32 time_now;
494   GFileMonitor *monitor;
495 } ForEachData;
496
497 static gboolean
498 calc_min_time (GFileMonitor *monitor, 
499                RateLimiter *limiter, 
500                guint32 time_now, 
501                guint32 *min_time)
502 {
503   gboolean delete_me;
504   guint32 expire_at;
505
506   delete_me = TRUE;
507
508   if (limiter->last_sent_change_time != 0)
509     {
510       /* Set a timeout at 2*rate limit so that we can clear out the change from the hash eventualy */
511       expire_at = limiter->last_sent_change_time + 2 * monitor->priv->rate_limit_msec;
512
513       if (time_difference (time_now, expire_at) > 0)
514         {
515           delete_me = FALSE;
516           *min_time = MIN (*min_time,
517                            time_difference (time_now, expire_at));
518         }
519     }
520
521   if (limiter->send_delayed_change_at != 0)
522     {
523       delete_me = FALSE;
524       *min_time = MIN (*min_time,
525                        time_difference (time_now, limiter->send_delayed_change_at));
526     }
527
528   if (limiter->send_virtual_changes_done_at != 0)
529     {
530       delete_me = FALSE;
531       *min_time = MIN (*min_time,
532                        time_difference (time_now, limiter->send_virtual_changes_done_at));
533     }
534
535   return delete_me;
536 }
537
538 static gboolean
539 foreach_rate_limiter_fire (gpointer key,
540                            gpointer value,
541                            gpointer user_data)
542 {
543   RateLimiter *limiter = value;
544   ForEachData *data = user_data;
545
546   if (limiter->send_delayed_change_at != 0 &&
547       time_difference (data->time_now, limiter->send_delayed_change_at) == 0)
548     rate_limiter_send_delayed_change_now (data->monitor, limiter, data->time_now);
549   
550   if (limiter->send_virtual_changes_done_at != 0 &&
551       time_difference (data->time_now, limiter->send_virtual_changes_done_at) == 0)
552     rate_limiter_send_virtual_changes_done_now (data->monitor, limiter);
553   
554   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
555 }
556
557 static gboolean 
558 rate_limiter_timeout (gpointer timeout_data)
559 {
560   GFileMonitor *monitor = timeout_data;
561   ForEachData data;
562   GSource *source;
563   
564   data.min_time = G_MAXUINT32;
565   data.monitor = monitor;
566   data.time_now = get_time_msecs ();
567   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
568                                foreach_rate_limiter_fire,
569                                &data);
570   
571   /* Remove old timeout */
572   if (monitor->priv->timeout)
573     {
574       g_source_destroy (monitor->priv->timeout);
575       g_source_unref (monitor->priv->timeout);
576       monitor->priv->timeout = NULL;
577       monitor->priv->timeout_fires_at = 0;
578     }
579   
580   /* Set up new timeout */
581   if (data.min_time != G_MAXUINT32)
582     {
583       source = g_timeout_source_new (data.min_time + 1); /* + 1 to make sure we've really passed the time */
584       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
585       g_source_attach (source, monitor->priv->context);
586       
587       monitor->priv->timeout = source;
588       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
589     }
590   
591   return FALSE;
592 }
593
594 static gboolean
595 foreach_rate_limiter_update (gpointer key,
596                              gpointer value,
597                              gpointer user_data)
598 {
599   RateLimiter *limiter = value;
600   ForEachData *data = user_data;
601
602   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
603 }
604
605 static void
606 update_rate_limiter_timeout (GFileMonitor *monitor, 
607                              guint new_time)
608 {
609   ForEachData data;
610   GSource *source;
611   
612   if (monitor->priv->timeout_fires_at != 0 && new_time != 0 &&
613       time_difference (new_time, monitor->priv->timeout_fires_at) == 0)
614     return; /* Nothing to do, we already fire earlier than that */
615
616   data.min_time = G_MAXUINT32;
617   data.monitor = monitor;
618   data.time_now = get_time_msecs ();
619   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
620                                foreach_rate_limiter_update,
621                                &data);
622
623   /* Remove old timeout */
624   if (monitor->priv->timeout)
625     {
626       g_source_destroy (monitor->priv->timeout);
627       g_source_unref (monitor->priv->timeout);
628       monitor->priv->timeout_fires_at = 0;
629       monitor->priv->timeout = NULL;
630     }
631
632   /* Set up new timeout */
633   if (data.min_time != G_MAXUINT32)
634     {
635       source = g_timeout_source_new (data.min_time + 1);  /* + 1 to make sure we've really passed the time */
636       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
637       g_source_attach (source, monitor->priv->context);
638       
639       monitor->priv->timeout = source;
640       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
641     }
642 }
643
644 /**
645  * g_file_monitor_emit_event:
646  * @monitor: a #GFileMonitor.
647  * @child: a #GFile.
648  * @other_file: a #GFile.
649  * @event_type: a set of #GFileMonitorEvent flags.
650  * 
651  * Emits the #GFileMonitor::changed signal if a change
652  * has taken place. Should be called from file monitor 
653  * implementations only.
654  *
655  * The signal will be emitted from an idle handler (in the <link
656  * linkend="g-main-context-push-thread-default">thread-default main
657  * context</link>).
658  **/
659 void
660 g_file_monitor_emit_event (GFileMonitor      *monitor,
661                            GFile             *child,
662                            GFile             *other_file,
663                            GFileMonitorEvent  event_type)
664 {
665   guint32 time_now, since_last;
666   gboolean emit_now;
667   RateLimiter *limiter;
668
669   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
670   g_return_if_fail (G_IS_FILE (child));
671
672   limiter = g_hash_table_lookup (monitor->priv->rate_limiter, child);
673
674   if (event_type != G_FILE_MONITOR_EVENT_CHANGED)
675     {
676       if (limiter)
677         {
678           rate_limiter_send_delayed_change_now (monitor, limiter, get_time_msecs ());
679           if (event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT)
680             limiter->send_virtual_changes_done_at = 0;
681           else
682             rate_limiter_send_virtual_changes_done_now (monitor, limiter);
683           update_rate_limiter_timeout (monitor, 0);
684         }
685       emit_in_idle (monitor, child, other_file, event_type);
686     }
687   else
688     {
689       /* Changed event, rate limit */
690       time_now = get_time_msecs ();
691       emit_now = TRUE;
692       
693       if (limiter)
694         {
695           since_last = time_difference (limiter->last_sent_change_time, time_now);
696           if (since_last < monitor->priv->rate_limit_msec)
697             {
698               /* We ignore this change, but arm a timer so that we can fire it later if we
699                  don't get any other events (that kill this timeout) */
700               emit_now = FALSE;
701               if (limiter->send_delayed_change_at == 0)
702                 {
703                   limiter->send_delayed_change_at = time_now + monitor->priv->rate_limit_msec;
704                   update_rate_limiter_timeout (monitor, limiter->send_delayed_change_at);
705                 }
706             }
707         }
708       
709       if (limiter == NULL)
710         limiter = new_limiter (monitor, child);
711       
712       if (emit_now)
713         {
714           emit_in_idle (monitor, child, other_file, event_type);
715           
716           limiter->last_sent_change_time = time_now;
717           limiter->send_delayed_change_at = 0;
718           /* Set a timeout of 2*rate limit so that we can clear out the change from the hash eventualy */
719           update_rate_limiter_timeout (monitor, time_now + 2 * monitor->priv->rate_limit_msec);
720         }
721       
722       /* Schedule a virtual change done. This is removed if we get a real one, and
723          postponed if we get more change events. */
724       
725       limiter->send_virtual_changes_done_at = time_now + DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS * 1000;
726       update_rate_limiter_timeout (monitor, limiter->send_virtual_changes_done_at);
727     }
728 }
729
730 #define __G_FILE_MONITOR_C__
731 #include "gioaliasdef.c"