gio: Use the new private instance data declaration
[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 typedef struct {
66   GFile *file;
67   guint32 last_sent_change_time; /* 0 == not sent */
68   guint32 send_delayed_change_at; /* 0 == never */
69   guint32 send_virtual_changes_done_at; /* 0 == never */
70 } RateLimiter;
71
72 struct _GFileMonitorPrivate {
73   gboolean cancelled;
74   int rate_limit_msec;
75
76   /* Rate limiting change events */
77   GHashTable *rate_limiter;
78
79   GMutex mutex;
80   GSource *pending_file_change_source;
81   GSList *pending_file_changes; /* FileChange */
82
83   GSource *timeout;
84   guint32 timeout_fires_at;
85
86   GMainContext *context;
87 };
88
89 enum {
90   PROP_0,
91   PROP_RATE_LIMIT,
92   PROP_CANCELLED
93 };
94
95 /* work around a limitation of the aliasing foo */
96 #undef g_file_monitor
97
98 G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GFileMonitor, g_file_monitor, G_TYPE_OBJECT)
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   g_main_context_unref (monitor->priv->context);
180   g_mutex_clear (&monitor->priv->mutex);
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_free_full (priv->pending_file_changes, (GDestroyNotify) file_change_free);
201   priv->pending_file_changes = NULL;
202
203   /* Make sure we cancel on last unref */
204   g_file_monitor_cancel (monitor);
205
206   G_OBJECT_CLASS (g_file_monitor_parent_class)->dispose (object);
207 }
208
209 static void
210 g_file_monitor_class_init (GFileMonitorClass *klass)
211 {
212   GObjectClass *object_class;
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_EVENT_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_file_monitor_get_private (monitor);
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_ref_thread_default ();
273   g_mutex_init (&monitor->priv->mutex);
274 }
275
276 /**
277  * g_file_monitor_is_cancelled:
278  * @monitor: a #GFileMonitor
279  * 
280  * Returns whether the monitor is canceled.
281  *
282  * Returns: %TRUE if monitor is canceled. %FALSE otherwise.
283  **/
284 gboolean
285 g_file_monitor_is_cancelled (GFileMonitor *monitor)
286 {
287   gboolean res;
288
289   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
290
291   G_LOCK (cancelled);
292   res = monitor->priv->cancelled;
293   G_UNLOCK (cancelled);
294   
295   return res;
296 }
297
298 /**
299  * g_file_monitor_cancel:
300  * @monitor: a #GFileMonitor.
301  * 
302  * Cancels a file monitor.
303  * 
304  * Returns: %TRUE if monitor was cancelled.
305  **/
306 gboolean
307 g_file_monitor_cancel (GFileMonitor* monitor)
308 {
309   GFileMonitorClass *klass;
310   
311   g_return_val_if_fail (G_IS_FILE_MONITOR (monitor), FALSE);
312   
313   G_LOCK (cancelled);
314   if (monitor->priv->cancelled)
315     {
316       G_UNLOCK (cancelled);
317       return TRUE;
318     }
319   
320   monitor->priv->cancelled = TRUE;
321   G_UNLOCK (cancelled);
322   
323   g_object_notify (G_OBJECT (monitor), "cancelled");
324
325   klass = G_FILE_MONITOR_GET_CLASS (monitor);
326   return (* klass->cancel) (monitor);
327 }
328
329 /**
330  * g_file_monitor_set_rate_limit:
331  * @monitor: a #GFileMonitor.
332  * @limit_msecs: a non-negative integer with the limit in milliseconds
333  *     to poll for changes
334  *
335  * Sets the rate limit to which the @monitor will report
336  * consecutive change events to the same file.
337  */
338 void
339 g_file_monitor_set_rate_limit (GFileMonitor *monitor,
340                                gint          limit_msecs)
341 {
342   GFileMonitorPrivate *priv;
343
344   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
345   g_return_if_fail (limit_msecs >= 0);
346
347   priv = monitor->priv;
348   if (priv->rate_limit_msec != limit_msecs)
349     {
350       monitor->priv->rate_limit_msec = limit_msecs;
351       g_object_notify (G_OBJECT (monitor), "rate-limit");
352     }
353 }
354
355 struct _FileChange {
356   GFile             *child;
357   GFile             *other_file;
358   GFileMonitorEvent  event_type;
359 };
360
361 static void
362 file_change_free (FileChange *change)
363 {
364   g_object_unref (change->child);
365   if (change->other_file)
366     g_object_unref (change->other_file);
367   
368   g_slice_free (FileChange, change);
369 }
370
371 static gboolean
372 emit_cb (gpointer data)
373 {
374   GFileMonitor *monitor = G_FILE_MONITOR (data);
375   GSList *pending, *iter;
376
377   g_mutex_lock (&monitor->priv->mutex);
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   g_mutex_unlock (&monitor->priv->mutex);
386
387   g_object_ref (monitor);
388   for (iter = pending; iter; iter = iter->next)
389     {
390        FileChange *change = iter->data;
391
392        g_signal_emit (monitor, signals[CHANGED], 0,
393                       change->child, change->other_file, change->event_type);
394        file_change_free (change);
395     }
396   g_slist_free (pending);
397   g_object_unref (monitor);
398
399   return FALSE;
400 }
401
402 static void
403 emit_in_idle (GFileMonitor      *monitor,
404               GFile             *child,
405               GFile             *other_file,
406               GFileMonitorEvent  event_type)
407 {
408   GSource *source;
409   FileChange *change;
410   GFileMonitorPrivate *priv;
411
412   priv = monitor->priv;
413
414   change = g_slice_new (FileChange);
415
416   change->child = g_object_ref (child);
417   if (other_file)
418     change->other_file = g_object_ref (other_file);
419   else
420     change->other_file = NULL;
421   change->event_type = event_type;
422
423   g_mutex_lock (&monitor->priv->mutex);
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   g_mutex_unlock (&monitor->priv->mutex);
439 }
440
441 static guint32
442 get_time_msecs (void)
443 {
444   return g_get_monotonic_time () / G_TIME_SPAN_MILLISECOND;
445 }
446
447 static guint32
448 time_difference (guint32 from, guint32 to)
449 {
450   if (from > to)
451     return 0;
452   return to - from;
453 }
454
455 /* Change event rate limiting support: */
456
457 static RateLimiter *
458 new_limiter (GFileMonitor *monitor,
459              GFile             *file)
460 {
461   RateLimiter *limiter;
462
463   limiter = g_slice_new0 (RateLimiter);
464   limiter->file = g_object_ref (file);
465   g_hash_table_insert (monitor->priv->rate_limiter, file, limiter);
466   
467   return limiter;
468 }
469
470 static void
471 rate_limiter_send_virtual_changes_done_now (GFileMonitor *monitor, 
472                                             RateLimiter  *limiter)
473 {
474   if (limiter->send_virtual_changes_done_at != 0)
475     {
476       emit_in_idle (monitor, limiter->file, NULL,
477                     G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT);
478       limiter->send_virtual_changes_done_at = 0;
479     }
480 }
481
482 static void
483 rate_limiter_send_delayed_change_now (GFileMonitor *monitor, 
484                                       RateLimiter *limiter, 
485                                       guint32 time_now)
486 {
487   if (limiter->send_delayed_change_at != 0)
488     {
489       emit_in_idle (monitor, 
490                     limiter->file, NULL,
491                     G_FILE_MONITOR_EVENT_CHANGED);
492       limiter->send_delayed_change_at = 0;
493       limiter->last_sent_change_time = time_now;
494     }
495 }
496
497 typedef struct {
498   guint32 min_time;
499   guint32 time_now;
500   GFileMonitor *monitor;
501 } ForEachData;
502
503 static gboolean
504 calc_min_time (GFileMonitor *monitor, 
505                RateLimiter *limiter, 
506                guint32 time_now, 
507                guint32 *min_time)
508 {
509   gboolean delete_me;
510   guint32 expire_at;
511
512   delete_me = TRUE;
513
514   if (limiter->last_sent_change_time != 0)
515     {
516       /* Set a timeout at 2*rate limit so that we can clear out the change from the hash eventually */
517       expire_at = limiter->last_sent_change_time + 2 * monitor->priv->rate_limit_msec;
518
519       if (time_difference (time_now, expire_at) > 0)
520         {
521           delete_me = FALSE;
522           *min_time = MIN (*min_time,
523                            time_difference (time_now, expire_at));
524         }
525     }
526
527   if (limiter->send_delayed_change_at != 0)
528     {
529       delete_me = FALSE;
530       *min_time = MIN (*min_time,
531                        time_difference (time_now, limiter->send_delayed_change_at));
532     }
533
534   if (limiter->send_virtual_changes_done_at != 0)
535     {
536       delete_me = FALSE;
537       *min_time = MIN (*min_time,
538                        time_difference (time_now, limiter->send_virtual_changes_done_at));
539     }
540
541   return delete_me;
542 }
543
544 static gboolean
545 foreach_rate_limiter_fire (gpointer key,
546                            gpointer value,
547                            gpointer user_data)
548 {
549   RateLimiter *limiter = value;
550   ForEachData *data = user_data;
551
552   if (limiter->send_delayed_change_at != 0 &&
553       time_difference (data->time_now, limiter->send_delayed_change_at) == 0)
554     rate_limiter_send_delayed_change_now (data->monitor, limiter, data->time_now);
555   
556   if (limiter->send_virtual_changes_done_at != 0 &&
557       time_difference (data->time_now, limiter->send_virtual_changes_done_at) == 0)
558     rate_limiter_send_virtual_changes_done_now (data->monitor, limiter);
559   
560   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
561 }
562
563 static gboolean 
564 rate_limiter_timeout (gpointer timeout_data)
565 {
566   GFileMonitor *monitor = timeout_data;
567   ForEachData data;
568   GSource *source;
569   
570   data.min_time = G_MAXUINT32;
571   data.monitor = monitor;
572   data.time_now = get_time_msecs ();
573   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
574                                foreach_rate_limiter_fire,
575                                &data);
576   
577   /* Remove old timeout */
578   if (monitor->priv->timeout)
579     {
580       g_source_destroy (monitor->priv->timeout);
581       g_source_unref (monitor->priv->timeout);
582       monitor->priv->timeout = NULL;
583       monitor->priv->timeout_fires_at = 0;
584     }
585   
586   /* Set up new timeout */
587   if (data.min_time != G_MAXUINT32)
588     {
589       source = g_timeout_source_new (data.min_time + 1); /* + 1 to make sure we've really passed the time */
590       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
591       g_source_attach (source, monitor->priv->context);
592       
593       monitor->priv->timeout = source;
594       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
595     }
596   
597   return FALSE;
598 }
599
600 static gboolean
601 foreach_rate_limiter_update (gpointer key,
602                              gpointer value,
603                              gpointer user_data)
604 {
605   RateLimiter *limiter = value;
606   ForEachData *data = user_data;
607
608   return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time);
609 }
610
611 static void
612 update_rate_limiter_timeout (GFileMonitor *monitor, 
613                              guint new_time)
614 {
615   ForEachData data;
616   GSource *source;
617   
618   if (monitor->priv->timeout_fires_at != 0 && new_time != 0 &&
619       time_difference (new_time, monitor->priv->timeout_fires_at) == 0)
620     return; /* Nothing to do, we already fire earlier than that */
621
622   data.min_time = G_MAXUINT32;
623   data.monitor = monitor;
624   data.time_now = get_time_msecs ();
625   g_hash_table_foreach_remove (monitor->priv->rate_limiter,
626                                foreach_rate_limiter_update,
627                                &data);
628
629   /* Remove old timeout */
630   if (monitor->priv->timeout)
631     {
632       g_source_destroy (monitor->priv->timeout);
633       g_source_unref (monitor->priv->timeout);
634       monitor->priv->timeout_fires_at = 0;
635       monitor->priv->timeout = NULL;
636     }
637
638   /* Set up new timeout */
639   if (data.min_time != G_MAXUINT32)
640     {
641       source = g_timeout_source_new (data.min_time + 1);  /* + 1 to make sure we've really passed the time */
642       g_source_set_callback (source, rate_limiter_timeout, monitor, NULL);
643       g_source_attach (source, monitor->priv->context);
644       
645       monitor->priv->timeout = source;
646       monitor->priv->timeout_fires_at = data.time_now + data.min_time; 
647     }
648 }
649
650 /**
651  * g_file_monitor_emit_event:
652  * @monitor: a #GFileMonitor.
653  * @child: a #GFile.
654  * @other_file: a #GFile.
655  * @event_type: a set of #GFileMonitorEvent flags.
656  * 
657  * Emits the #GFileMonitor::changed signal if a change
658  * has taken place. Should be called from file monitor 
659  * implementations only.
660  *
661  * The signal will be emitted from an idle handler (in the <link
662  * linkend="g-main-context-push-thread-default">thread-default main
663  * context</link>).
664  **/
665 void
666 g_file_monitor_emit_event (GFileMonitor      *monitor,
667                            GFile             *child,
668                            GFile             *other_file,
669                            GFileMonitorEvent  event_type)
670 {
671   guint32 time_now, since_last;
672   gboolean emit_now;
673   RateLimiter *limiter;
674
675   g_return_if_fail (G_IS_FILE_MONITOR (monitor));
676   g_return_if_fail (G_IS_FILE (child));
677
678   limiter = g_hash_table_lookup (monitor->priv->rate_limiter, child);
679
680   if (event_type != G_FILE_MONITOR_EVENT_CHANGED)
681     {
682       if (limiter)
683         {
684           rate_limiter_send_delayed_change_now (monitor, limiter, get_time_msecs ());
685           if (event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT)
686             limiter->send_virtual_changes_done_at = 0;
687           else
688             rate_limiter_send_virtual_changes_done_now (monitor, limiter);
689           update_rate_limiter_timeout (monitor, 0);
690         }
691       emit_in_idle (monitor, child, other_file, event_type);
692     }
693   else
694     {
695       /* Changed event, rate limit */
696       time_now = get_time_msecs ();
697       emit_now = TRUE;
698       
699       if (limiter)
700         {
701           since_last = time_difference (limiter->last_sent_change_time, time_now);
702           if (since_last < monitor->priv->rate_limit_msec)
703             {
704               /* We ignore this change, but arm a timer so that we can fire it later if we
705                  don't get any other events (that kill this timeout) */
706               emit_now = FALSE;
707               if (limiter->send_delayed_change_at == 0)
708                 {
709                   limiter->send_delayed_change_at = time_now + monitor->priv->rate_limit_msec;
710                   update_rate_limiter_timeout (monitor, limiter->send_delayed_change_at);
711                 }
712             }
713         }
714       
715       if (limiter == NULL)
716         limiter = new_limiter (monitor, child);
717       
718       if (emit_now)
719         {
720           emit_in_idle (monitor, child, other_file, event_type);
721           
722           limiter->last_sent_change_time = time_now;
723           limiter->send_delayed_change_at = 0;
724           /* Set a timeout of 2*rate limit so that we can clear out the change from the hash eventually */
725           update_rate_limiter_timeout (monitor, time_now + 2 * monitor->priv->rate_limit_msec);
726         }
727       
728       /* Schedule a virtual change done. This is removed if we get a real one, and
729          postponed if we get more change events. */
730       
731       limiter->send_virtual_changes_done_at = time_now + DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS * 1000;
732       update_rate_limiter_timeout (monitor, limiter->send_virtual_changes_done_at);
733     }
734 }