Merge remote branch 'gvdb/master'
[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 or #NULL.
228    * @event_type: a #GFileMonitorEvent.
229    *
230    * Emitted when @file has been changed.
231    *
232    * If using #G_FILE_MONITOR_SEND_MOVED flag and @event_type is
233    * #G_FILE_MONITOR_SEND_MOVED, @file will be set to a #GFile containing the
234    * old path, and @other_file will be set to a #GFile containing the new path.
235    *
236    * In all the other cases, @other_file will be set to #NULL.
237    **/
238   signals[CHANGED] =
239     g_signal_new (I_("changed"),
240                   G_TYPE_FILE_MONITOR,
241                   G_SIGNAL_RUN_LAST,
242                   G_STRUCT_OFFSET (GFileMonitorClass, changed),
243                   NULL, NULL,
244                   _gio_marshal_VOID__OBJECT_OBJECT_ENUM,
245                   G_TYPE_NONE, 3,
246                   G_TYPE_FILE, G_TYPE_FILE, G_TYPE_FILE_MONITOR_EVENT);
247
248   g_object_class_install_property (object_class,
249                                    PROP_RATE_LIMIT,
250                                    g_param_spec_int ("rate-limit",
251                                                      P_("Rate limit"),
252                                                      P_("The limit of the monitor to watch for changes, in milliseconds"),
253                                                      0, G_MAXINT,
254                                                      DEFAULT_RATE_LIMIT_MSECS,
255                                                      G_PARAM_READWRITE|
256                                                      G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
257
258   g_object_class_install_property (object_class,
259                                    PROP_CANCELLED,
260                                    g_param_spec_boolean ("cancelled",
261                                                          P_("Cancelled"),
262                                                          P_("Whether the monitor has been cancelled"),
263                                                          FALSE,
264                                                          G_PARAM_READABLE|
265                                                          G_PARAM_STATIC_NAME|G_PARAM_STATIC_NICK|G_PARAM_STATIC_BLURB));
266 }
267
268 static void
269 g_file_monitor_init (GFileMonitor *monitor)
270 {
271   monitor->priv = G_TYPE_INSTANCE_GET_PRIVATE (monitor,
272                                                G_TYPE_FILE_MONITOR,
273                                                GFileMonitorPrivate);
274   monitor->priv->rate_limit_msec = DEFAULT_RATE_LIMIT_MSECS;
275   monitor->priv->rate_limiter = g_hash_table_new_full (g_file_hash, (GEqualFunc)g_file_equal,
276                                                        NULL, (GDestroyNotify) rate_limiter_free);
277   monitor->priv->context = g_main_context_get_thread_default ();
278 }
279
280 /**
281  * g_file_monitor_is_cancelled:
282  * @monitor: a #GFileMonitor
283  * 
284  * Returns whether the monitor is canceled.
285  *
286  * Returns: %TRUE if monitor is canceled. %FALSE otherwise.
287  **/
288 gboolean
289 g_file_monitor_is_cancelled (GFileMonitor *monitor)
290 {
291   gboolean res;
292
293   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
294
295   G_LOCK (cancelled);
296   res = monitor->priv->cancelled;
297   G_UNLOCK (cancelled);
298   
299   return res;
300 }
301
302 /**
303  * g_file_monitor_cancel:
304  * @monitor: a #GFileMonitor.
305  * 
306  * Cancels a file monitor.
307  * 
308  * Returns: %TRUE if monitor was cancelled.
309  **/
310 gboolean
311 g_file_monitor_cancel (GFileMonitor* monitor)
312 {
313   GFileMonitorClass *klass;
314   
315   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
316   
317   G_LOCK (cancelled);
318   if (monitor->priv->cancelled)
319     {
320       G_UNLOCK (cancelled);
321       return TRUE;
322     }
323   
324   monitor->priv->cancelled = TRUE;
325   G_UNLOCK (cancelled);
326   
327   g_object_notify (G_OBJECT (monitor), "cancelled");
328
329   klass = G_FILE_MONITOR_GET_CLASS (monitor);
330   return (* klass->cancel) (monitor);
331 }
332
333 /**
334  * g_file_monitor_set_rate_limit:
335  * @monitor: a #GFileMonitor.
336  * @limit_msecs: a non-negative integer with the limit in milliseconds
337  *     to poll for changes
338  *
339  * Sets the rate limit to which the @monitor will report
340  * consecutive change events to the same file.
341  */
342 void
343 g_file_monitor_set_rate_limit (GFileMonitor *monitor,
344                                gint          limit_msecs)
345 {
346   GFileMonitorPrivate *priv;
347
348   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
349   g_return_if_fail (limit_msecs >= 0);
350
351   priv = monitor->priv;
352   if (priv->rate_limit_msec != limit_msecs)
353     {
354       monitor->priv->rate_limit_msec = limit_msecs;
355       g_object_notify (G_OBJECT (monitor), "rate-limit");
356     }
357 }
358
359 struct _FileChange {
360   GFile             *child;
361   GFile             *other_file;
362   GFileMonitorEvent  event_type;
363 };
364
365 static void
366 file_change_free (FileChange *change)
367 {
368   g_object_unref (change->child);
369   if (change->other_file)
370     g_object_unref (change->other_file);
371   
372   g_slice_free (FileChange, change);
373 }
374
375 static gboolean
376 emit_cb (gpointer data)
377 {
378   GFileMonitor *monitor = G_FILE_MONITOR (data);
379   GSList *pending, *iter;
380   
381   pending = g_slist_reverse (monitor->priv->pending_file_changes);
382   monitor->priv->pending_file_changes = NULL;
383   if (monitor->priv->pending_file_change_source)
384     {
385       g_source_unref (monitor->priv->pending_file_change_source);
386       monitor->priv->pending_file_change_source = NULL;
387     }
388
389   g_object_ref (monitor);
390   for (iter = pending; iter; iter = iter->next)
391     {
392        FileChange *change = iter->data;
393        g_signal_emit (monitor, signals[CHANGED], 0,
394                       change->child, change->other_file, change->event_type);
395        file_change_free (change);
396     }
397   g_slist_free (pending);
398   g_object_unref (monitor);
399
400   return FALSE;
401 }
402
403 static void
404 emit_in_idle (GFileMonitor      *monitor,
405               GFile             *child,
406               GFile             *other_file,
407               GFileMonitorEvent  event_type)
408 {
409   GSource *source;
410   FileChange *change;
411   GFileMonitorPrivate *priv;
412
413   priv = monitor->priv;
414
415   change = g_slice_new (FileChange);
416
417   change->child = g_object_ref (child);
418   if (other_file)
419     change->other_file = g_object_ref (other_file);
420   else
421     change->other_file = NULL;
422   change->event_type = event_type;
423
424   if (!priv->pending_file_change_source)
425     {
426       source = g_idle_source_new ();
427       priv->pending_file_change_source = source;
428       g_source_set_priority (source, 0);
429
430       /* We don't ref monitor here - instead dispose will free any
431        * pending idles.
432        */
433       g_source_set_callback (source, emit_cb, monitor, NULL);
434       g_source_attach (source, monitor->priv->context);
435     }
436   /* We reverse this in the processor */
437   priv->pending_file_changes = g_slist_prepend (priv->pending_file_changes, change);
438 }
439
440 static guint32
441 get_time_msecs (void)
442 {
443   return g_thread_gettime() / (1000 * 1000);
444 }
445
446 static guint32
447 time_difference (guint32 from, guint32 to)
448 {
449   if (from > to)
450     return 0;
451   return to - from;
452 }
453
454 /* Change event rate limiting support: */
455
456 static RateLimiter *
457 new_limiter (GFileMonitor *monitor,
458              GFile             *file)
459 {
460   RateLimiter *limiter;
461
462   limiter = g_slice_new0 (RateLimiter);
463   limiter->file = g_object_ref (file);
464   g_hash_table_insert (monitor->priv->rate_limiter, file, limiter);
465   
466   return limiter;
467 }
468
469 static void
470 rate_limiter_send_virtual_changes_done_now (GFileMonitor *monitor, 
471                                             RateLimiter  *limiter)
472 {
473   if (limiter->send_virtual_changes_done_at != 0)
474     {
475       emit_in_idle (monitor, limiter->file, NULL,
476                     G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT);
477       limiter->send_virtual_changes_done_at = 0;
478     }
479 }
480
481 static void
482 rate_limiter_send_delayed_change_now (GFileMonitor *monitor, 
483                                       RateLimiter *limiter, 
484                                       guint32 time_now)
485 {
486   if (limiter->send_delayed_change_at != 0)
487     {
488       emit_in_idle (monitor, 
489                     limiter->file, NULL,
490                     G_FILE_MONITOR_EVENT_CHANGED);
491       limiter->send_delayed_change_at = 0;
492       limiter->last_sent_change_time = time_now;
493     }
494 }
495
496 typedef struct {
497   guint32 min_time;
498   guint32 time_now;
499   GFileMonitor *monitor;
500 } ForEachData;
501
502 static gboolean
503 calc_min_time (GFileMonitor *monitor, 
504                RateLimiter *limiter, 
505                guint32 time_now, 
506                guint32 *min_time)
507 {
508   gboolean delete_me;
509   guint32 expire_at;
510
511   delete_me = TRUE;
512
513   if (limiter->last_sent_change_time != 0)
514     {
515       /* Set a timeout at 2*rate limit so that we can clear out the change from the hash eventualy */
516       expire_at = limiter->last_sent_change_time + 2 * monitor->priv->rate_limit_msec;
517
518       if (time_difference (time_now, expire_at) > 0)
519         {
520           delete_me = FALSE;
521           *min_time = MIN (*min_time,
522                            time_difference (time_now, expire_at));
523         }
524     }
525
526   if (limiter->send_delayed_change_at != 0)
527     {
528       delete_me = FALSE;
529       *min_time = MIN (*min_time,
530                        time_difference (time_now, limiter->send_delayed_change_at));
531     }
532
533   if (limiter->send_virtual_changes_done_at != 0)
534     {
535       delete_me = FALSE;
536       *min_time = MIN (*min_time,
537                        time_difference (time_now, limiter->send_virtual_changes_done_at));
538     }
539
540   return delete_me;
541 }
542
543 static gboolean
544 foreach_rate_limiter_fire (gpointer key,
545                            gpointer value,
546                            gpointer user_data)
547 {
548   RateLimiter *limiter = value;
549   ForEachData *data = user_data;
550
551   if (limiter->send_delayed_change_at != 0 &&
552       time_difference (data->time_now, limiter->send_delayed_change_at) == 0)
553     rate_limiter_send_delayed_change_now (data->monitor, limiter, data->time_now);
554   
555   if (limiter->send_virtual_changes_done_at != 0 &&
556       time_difference (data->time_now, limiter->send_virtual_changes_done_at) == 0)
557     rate_limiter_send_virtual_changes_done_now (data->monitor, limiter);
558   
559   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
560 }
561
562 static gboolean 
563 rate_limiter_timeout (gpointer timeout_data)
564 {
565   GFileMonitor *monitor = timeout_data;
566   ForEachData data;
567   GSource *source;
568   
569   data.min_time = G_MAXUINT32;
570   data.monitor = monitor;
571   data.time_now = get_time_msecs ();
572   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
573                                foreach_rate_limiter_fire,
574                                &data);
575   
576   /* Remove old timeout */
577   if (monitor->priv->timeout)
578     {
579       g_source_destroy (monitor->priv->timeout);
580       g_source_unref (monitor->priv->timeout);
581       monitor->priv->timeout = NULL;
582       monitor->priv->timeout_fires_at = 0;
583     }
584   
585   /* Set up new timeout */
586   if (data.min_time != G_MAXUINT32)
587     {
588       source = g_timeout_source_new (data.min_time + 1); /* + 1 to make sure we've really passed the time */
589       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
590       g_source_attach (source, monitor->priv->context);
591       
592       monitor->priv->timeout = source;
593       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
594     }
595   
596   return FALSE;
597 }
598
599 static gboolean
600 foreach_rate_limiter_update (gpointer key,
601                              gpointer value,
602                              gpointer user_data)
603 {
604   RateLimiter *limiter = value;
605   ForEachData *data = user_data;
606
607   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
608 }
609
610 static void
611 update_rate_limiter_timeout (GFileMonitor *monitor, 
612                              guint new_time)
613 {
614   ForEachData data;
615   GSource *source;
616   
617   if (monitor->priv->timeout_fires_at != 0 && new_time != 0 &&
618       time_difference (new_time, monitor->priv->timeout_fires_at) == 0)
619     return; /* Nothing to do, we already fire earlier than that */
620
621   data.min_time = G_MAXUINT32;
622   data.monitor = monitor;
623   data.time_now = get_time_msecs ();
624   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
625                                foreach_rate_limiter_update,
626                                &data);
627
628   /* Remove old timeout */
629   if (monitor->priv->timeout)
630     {
631       g_source_destroy (monitor->priv->timeout);
632       g_source_unref (monitor->priv->timeout);
633       monitor->priv->timeout_fires_at = 0;
634       monitor->priv->timeout = NULL;
635     }
636
637   /* Set up new timeout */
638   if (data.min_time != G_MAXUINT32)
639     {
640       source = g_timeout_source_new (data.min_time + 1);  /* + 1 to make sure we've really passed the time */
641       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
642       g_source_attach (source, monitor->priv->context);
643       
644       monitor->priv->timeout = source;
645       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
646     }
647 }
648
649 /**
650  * g_file_monitor_emit_event:
651  * @monitor: a #GFileMonitor.
652  * @child: a #GFile.
653  * @other_file: a #GFile.
654  * @event_type: a set of #GFileMonitorEvent flags.
655  * 
656  * Emits the #GFileMonitor::changed signal if a change
657  * has taken place. Should be called from file monitor 
658  * implementations only.
659  *
660  * The signal will be emitted from an idle handler (in the <link
661  * linkend="g-main-context-push-thread-default">thread-default main
662  * context</link>).
663  **/
664 void
665 g_file_monitor_emit_event (GFileMonitor      *monitor,
666                            GFile             *child,
667                            GFile             *other_file,
668                            GFileMonitorEvent  event_type)
669 {
670   guint32 time_now, since_last;
671   gboolean emit_now;
672   RateLimiter *limiter;
673
674   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
675   g_return_if_fail (G_IS_FILE (child));
676
677   limiter = g_hash_table_lookup (monitor->priv->rate_limiter, child);
678
679   if (event_type != G_FILE_MONITOR_EVENT_CHANGED)
680     {
681       if (limiter)
682         {
683           rate_limiter_send_delayed_change_now (monitor, limiter, get_time_msecs ());
684           if (event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT)
685             limiter->send_virtual_changes_done_at = 0;
686           else
687             rate_limiter_send_virtual_changes_done_now (monitor, limiter);
688           update_rate_limiter_timeout (monitor, 0);
689         }
690       emit_in_idle (monitor, child, other_file, event_type);
691     }
692   else
693     {
694       /* Changed event, rate limit */
695       time_now = get_time_msecs ();
696       emit_now = TRUE;
697       
698       if (limiter)
699         {
700           since_last = time_difference (limiter->last_sent_change_time, time_now);
701           if (since_last < monitor->priv->rate_limit_msec)
702             {
703               /* We ignore this change, but arm a timer so that we can fire it later if we
704                  don't get any other events (that kill this timeout) */
705               emit_now = FALSE;
706               if (limiter->send_delayed_change_at == 0)
707                 {
708                   limiter->send_delayed_change_at = time_now + monitor->priv->rate_limit_msec;
709                   update_rate_limiter_timeout (monitor, limiter->send_delayed_change_at);
710                 }
711             }
712         }
713       
714       if (limiter == NULL)
715         limiter = new_limiter (monitor, child);
716       
717       if (emit_now)
718         {
719           emit_in_idle (monitor, child, other_file, event_type);
720           
721           limiter->last_sent_change_time = time_now;
722           limiter->send_delayed_change_at = 0;
723           /* Set a timeout of 2*rate limit so that we can clear out the change from the hash eventualy */
724           update_rate_limiter_timeout (monitor, time_now + 2 * monitor->priv->rate_limit_msec);
725         }
726       
727       /* Schedule a virtual change done. This is removed if we get a real one, and
728          postponed if we get more change events. */
729       
730       limiter->send_virtual_changes_done_at = time_now + DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS * 1000;
731       update_rate_limiter_timeout (monitor, limiter->send_virtual_changes_done_at);
732     }
733 }