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