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