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