Use pipe2 when available
[platform/upstream/glib.git] / glib / gmain.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmain.c: Main loop abstraction, timeouts, and idle functions
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /*
24  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
28  */
29
30 /* 
31  * MT safe
32  */
33
34 #include "config.h"
35
36 /* Uncomment the next line (and the corresponding line in gpoll.c) to
37  * enable debugging printouts if the environment variable
38  * G_MAIN_POLL_DEBUG is set to some value.
39  */
40 /* #define G_MAIN_POLL_DEBUG */
41
42 #ifdef _WIN32
43 /* Always enable debugging printout on Windows, as it is more often
44  * needed there...
45  */
46 #define G_MAIN_POLL_DEBUG
47 #endif
48
49 #define _GNU_SOURCE  /* for pipe2 */
50
51 #include "glib.h"
52 #include "gthreadprivate.h"
53 #include <signal.h>
54 #include <sys/types.h>
55 #include <time.h>
56 #include <stdlib.h>
57 #ifdef HAVE_SYS_TIME_H
58 #include <sys/time.h>
59 #endif /* HAVE_SYS_TIME_H */
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #endif /* HAVE_UNISTD_H */
63 #include <errno.h>
64
65 #ifdef G_OS_WIN32
66 #define STRICT
67 #include <windows.h>
68 #endif /* G_OS_WIN32 */
69
70 #ifdef G_OS_BEOS
71 #include <sys/socket.h>
72 #include <sys/wait.h>
73 #endif /* G_OS_BEOS */
74
75 #ifdef G_OS_UNIX
76 #include <fcntl.h>
77 #include <sys/wait.h>
78 #endif
79
80 #include "galias.h"
81
82 /* Types */
83
84 typedef struct _GTimeoutSource GTimeoutSource;
85 typedef struct _GChildWatchSource GChildWatchSource;
86 typedef struct _GPollRec GPollRec;
87 typedef struct _GSourceCallback GSourceCallback;
88
89 typedef enum
90 {
91   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
92   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
93 } GSourceFlags;
94
95 #ifdef G_THREADS_ENABLED
96 typedef struct _GMainWaiter GMainWaiter;
97
98 struct _GMainWaiter
99 {
100   GCond *cond;
101   GMutex *mutex;
102 };
103 #endif  
104
105 typedef struct _GMainDispatch GMainDispatch;
106
107 struct _GMainDispatch
108 {
109   gint depth;
110   GSList *dispatching_sources; /* stack of current sources */
111 };
112
113 #ifdef G_MAIN_POLL_DEBUG
114 gboolean _g_main_poll_debug = FALSE;
115 #endif
116
117 struct _GMainContext
118 {
119 #ifdef G_THREADS_ENABLED
120   /* The following lock is used for both the list of sources
121    * and the list of poll records
122    */
123   GStaticMutex mutex;
124   GCond *cond;
125   GThread *owner;
126   guint owner_count;
127   GSList *waiters;
128 #endif  
129
130   gint ref_count;
131
132   GPtrArray *pending_dispatches;
133   gint timeout;                 /* Timeout for current iteration */
134
135   guint next_id;
136   GSource *source_list;
137   gint in_check_or_prepare;
138
139   GPollRec *poll_records;
140   guint n_poll_records;
141   GPollFD *cached_poll_array;
142   guint cached_poll_array_size;
143
144 #ifdef G_THREADS_ENABLED  
145 #ifndef G_OS_WIN32
146 /* this pipe is used to wake up the main loop when a source is added.
147  */
148   gint wake_up_pipe[2];
149 #else /* G_OS_WIN32 */
150   HANDLE wake_up_semaphore;
151 #endif /* G_OS_WIN32 */
152
153   GPollFD wake_up_rec;
154   gboolean poll_waiting;
155
156 /* Flag indicating whether the set of fd's changed during a poll */
157   gboolean poll_changed;
158 #endif /* G_THREADS_ENABLED */
159
160   GPollFunc poll_func;
161
162   GTimeVal current_time;
163   gboolean time_is_current;
164 };
165
166 struct _GSourceCallback
167 {
168   guint ref_count;
169   GSourceFunc func;
170   gpointer    data;
171   GDestroyNotify notify;
172 };
173
174 struct _GMainLoop
175 {
176   GMainContext *context;
177   gboolean is_running;
178   gint ref_count;
179 };
180
181 struct _GTimeoutSource
182 {
183   GSource     source;
184   GTimeVal    expiration;
185   guint       interval;
186   guint       granularity;
187 };
188
189 struct _GChildWatchSource
190 {
191   GSource     source;
192   GPid        pid;
193   gint        child_status;
194 #ifdef G_OS_WIN32
195   GPollFD     poll;
196 #else /* G_OS_WIN32 */
197   gint        count;
198   gboolean    child_exited;
199 #endif /* G_OS_WIN32 */
200 };
201
202 struct _GPollRec
203 {
204   GPollFD *fd;
205   GPollRec *next;
206   gint priority;
207 };
208
209 #ifdef G_THREADS_ENABLED
210 #define LOCK_CONTEXT(context) g_static_mutex_lock (&context->mutex)
211 #define UNLOCK_CONTEXT(context) g_static_mutex_unlock (&context->mutex)
212 #define G_THREAD_SELF g_thread_self ()
213 #else
214 #define LOCK_CONTEXT(context) (void)0
215 #define UNLOCK_CONTEXT(context) (void)0
216 #define G_THREAD_SELF NULL
217 #endif
218
219 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
220 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
221                                 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
222
223 #define SOURCE_UNREF(source, context)                       \
224    G_STMT_START {                                           \
225     if ((source)->ref_count > 1)                            \
226       (source)->ref_count--;                                \
227     else                                                    \
228       g_source_unref_internal ((source), (context), TRUE);  \
229    } G_STMT_END
230
231
232 /* Forward declarations */
233
234 static void g_source_unref_internal             (GSource      *source,
235                                                  GMainContext *context,
236                                                  gboolean      have_lock);
237 static void g_source_destroy_internal           (GSource      *source,
238                                                  GMainContext *context,
239                                                  gboolean      have_lock);
240 static void g_main_context_poll                 (GMainContext *context,
241                                                  gint          timeout,
242                                                  gint          priority,
243                                                  GPollFD      *fds,
244                                                  gint          n_fds);
245 static void g_main_context_add_poll_unlocked    (GMainContext *context,
246                                                  gint          priority,
247                                                  GPollFD      *fd);
248 static void g_main_context_remove_poll_unlocked (GMainContext *context,
249                                                  GPollFD      *fd);
250 static void g_main_context_wakeup_unlocked      (GMainContext *context);
251
252 static gboolean g_timeout_prepare  (GSource     *source,
253                                     gint        *timeout);
254 static gboolean g_timeout_check    (GSource     *source);
255 static gboolean g_timeout_dispatch (GSource     *source,
256                                     GSourceFunc  callback,
257                                     gpointer     user_data);
258 static gboolean g_child_watch_prepare  (GSource     *source,
259                                         gint        *timeout);
260 static gboolean g_child_watch_check    (GSource     *source);
261 static gboolean g_child_watch_dispatch (GSource     *source,
262                                         GSourceFunc  callback,
263                                         gpointer     user_data);
264 static gboolean g_idle_prepare     (GSource     *source,
265                                     gint        *timeout);
266 static gboolean g_idle_check       (GSource     *source);
267 static gboolean g_idle_dispatch    (GSource     *source,
268                                     GSourceFunc  callback,
269                                     gpointer     user_data);
270
271 G_LOCK_DEFINE_STATIC (main_loop);
272 static GMainContext *default_main_context;
273 static GSList *main_contexts_without_pipe = NULL;
274
275 #ifndef G_OS_WIN32
276 /* Child status monitoring code */
277 enum {
278   CHILD_WATCH_UNINITIALIZED,
279   CHILD_WATCH_INITIALIZED_SINGLE,
280   CHILD_WATCH_INITIALIZED_THREADED
281 };
282 static gint child_watch_init_state = CHILD_WATCH_UNINITIALIZED;
283 static gint child_watch_count = 1;
284 static gint child_watch_wake_up_pipe[2] = {0, 0};
285 #endif /* !G_OS_WIN32 */
286 G_LOCK_DEFINE_STATIC (main_context_list);
287 static GSList *main_context_list = NULL;
288
289 static gint timer_perturb = -1;
290
291 GSourceFuncs g_timeout_funcs =
292 {
293   g_timeout_prepare,
294   g_timeout_check,
295   g_timeout_dispatch,
296   NULL
297 };
298
299 GSourceFuncs g_child_watch_funcs =
300 {
301   g_child_watch_prepare,
302   g_child_watch_check,
303   g_child_watch_dispatch,
304   NULL
305 };
306
307 GSourceFuncs g_idle_funcs =
308 {
309   g_idle_prepare,
310   g_idle_check,
311   g_idle_dispatch,
312   NULL
313 };
314
315 /**
316  * g_main_context_ref:
317  * @context: a #GMainContext
318  * 
319  * Increases the reference count on a #GMainContext object by one.
320  *
321  * Returns: the @context that was passed in (since 2.6)
322  **/
323 GMainContext *
324 g_main_context_ref (GMainContext *context)
325 {
326   g_return_val_if_fail (context != NULL, NULL);
327   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL); 
328
329   g_atomic_int_inc (&context->ref_count);
330
331   return context;
332 }
333
334 static inline void
335 poll_rec_list_free (GMainContext *context,
336                     GPollRec     *list)
337 {
338   g_slice_free_chain (GPollRec, list, next);
339 }
340
341 /**
342  * g_main_context_unref:
343  * @context: a #GMainContext
344  * 
345  * Decreases the reference count on a #GMainContext object by one. If
346  * the result is zero, free the context and free all associated memory.
347  **/
348 void
349 g_main_context_unref (GMainContext *context)
350 {
351   GSource *source;
352   g_return_if_fail (context != NULL);
353   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0); 
354
355   if (!g_atomic_int_dec_and_test (&context->ref_count))
356     return;
357
358   G_LOCK (main_context_list);
359   main_context_list = g_slist_remove (main_context_list, context);
360   G_UNLOCK (main_context_list);
361
362   source = context->source_list;
363   while (source)
364     {
365       GSource *next = source->next;
366       g_source_destroy_internal (source, context, FALSE);
367       source = next;
368     }
369
370 #ifdef G_THREADS_ENABLED  
371   g_static_mutex_free (&context->mutex);
372 #endif
373
374   g_ptr_array_free (context->pending_dispatches, TRUE);
375   g_free (context->cached_poll_array);
376
377   poll_rec_list_free (context, context->poll_records);
378   
379 #ifdef G_THREADS_ENABLED
380   if (g_thread_supported())
381     {
382 #ifndef G_OS_WIN32
383       close (context->wake_up_pipe[0]);
384       close (context->wake_up_pipe[1]);
385 #else
386       CloseHandle (context->wake_up_semaphore);
387 #endif
388     } 
389   else
390     main_contexts_without_pipe = g_slist_remove (main_contexts_without_pipe, 
391                                                  context);
392
393   if (context->cond != NULL)
394     g_cond_free (context->cond);
395 #endif
396   
397   g_free (context);
398 }
399
400 #ifdef G_THREADS_ENABLED
401 static void 
402 g_main_context_init_pipe (GMainContext *context)
403 {
404 # ifndef G_OS_WIN32
405   if (context->wake_up_pipe[0] != -1)
406     return;
407
408 #ifdef HAVE_PIPE2
409   /* if this fails, we fall through and try pipe */
410   pipe2 (context->wake_up_pipe, O_CLOEXEC);
411 #endif
412   if (context->wake_up_pipe[0] == -1)
413     {
414       if (pipe (context->wake_up_pipe) < 0)
415         g_error ("Cannot create pipe main loop wake-up: %s\n",
416                  g_strerror (errno));
417  
418       fcntl (context->wake_up_pipe[0], F_SETFD, FD_CLOEXEC);
419       fcntl (context->wake_up_pipe[1], F_SETFD, FD_CLOEXEC);
420     }
421
422   context->wake_up_rec.fd = context->wake_up_pipe[0];
423   context->wake_up_rec.events = G_IO_IN;
424 # else
425   if (context->wake_up_semaphore != NULL)
426     return;
427   context->wake_up_semaphore = CreateSemaphore (NULL, 0, 100, NULL);
428   if (context->wake_up_semaphore == NULL)
429     g_error ("Cannot create wake-up semaphore: %s",
430              g_win32_error_message (GetLastError ()));
431   context->wake_up_rec.fd = (gintptr) context->wake_up_semaphore;
432   context->wake_up_rec.events = G_IO_IN;
433
434   if (_g_main_poll_debug)
435     g_print ("wake-up semaphore: %p\n", context->wake_up_semaphore);
436 # endif
437   g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
438 }
439
440 void
441 _g_main_thread_init (void)
442 {
443   GSList *curr = main_contexts_without_pipe;
444   while (curr)
445     {
446       g_main_context_init_pipe ((GMainContext *)curr->data);
447       curr = curr->next;
448     }
449   g_slist_free (main_contexts_without_pipe);
450   main_contexts_without_pipe = NULL;  
451 }
452 #endif /* G_THREADS_ENABLED */
453
454 /**
455  * g_main_context_new:
456  * 
457  * Creates a new #GMainContext structure.
458  * 
459  * Return value: the new #GMainContext
460  **/
461 GMainContext *
462 g_main_context_new (void)
463 {
464   GMainContext *context = g_new0 (GMainContext, 1);
465
466 #ifdef G_MAIN_POLL_DEBUG
467   {
468     static gboolean beenhere = FALSE;
469
470     if (!beenhere)
471       {
472         if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
473           _g_main_poll_debug = TRUE;
474         beenhere = TRUE;
475       }
476   }
477 #endif
478
479 #ifdef G_THREADS_ENABLED
480   g_static_mutex_init (&context->mutex);
481
482   context->owner = NULL;
483   context->waiters = NULL;
484
485 # ifndef G_OS_WIN32
486   context->wake_up_pipe[0] = -1;
487   context->wake_up_pipe[1] = -1;
488 # else
489   context->wake_up_semaphore = NULL;
490 # endif
491 #endif
492
493   context->ref_count = 1;
494
495   context->next_id = 1;
496   
497   context->source_list = NULL;
498   
499   context->poll_func = g_poll;
500   
501   context->cached_poll_array = NULL;
502   context->cached_poll_array_size = 0;
503   
504   context->pending_dispatches = g_ptr_array_new ();
505   
506   context->time_is_current = FALSE;
507   
508 #ifdef G_THREADS_ENABLED
509   if (g_thread_supported ())
510     g_main_context_init_pipe (context);
511   else
512     main_contexts_without_pipe = g_slist_prepend (main_contexts_without_pipe, 
513                                                   context);
514 #endif
515
516   G_LOCK (main_context_list);
517   main_context_list = g_slist_append (main_context_list, context);
518
519 #ifdef G_MAIN_POLL_DEBUG
520   if (_g_main_poll_debug)
521     g_print ("created context=%p\n", context);
522 #endif
523
524   G_UNLOCK (main_context_list);
525
526   return context;
527 }
528
529 /**
530  * g_main_context_default:
531  * 
532  * Returns the default main context. This is the main context used
533  * for main loop functions when a main loop is not explicitly
534  * specified.
535  * 
536  * Return value: the default main context.
537  **/
538 GMainContext *
539 g_main_context_default (void)
540 {
541   /* Slow, but safe */
542   
543   G_LOCK (main_loop);
544
545   if (!default_main_context)
546     {
547       default_main_context = g_main_context_new ();
548 #ifdef G_MAIN_POLL_DEBUG
549       if (_g_main_poll_debug)
550         g_print ("default context=%p\n", default_main_context);
551 #endif
552     }
553
554   G_UNLOCK (main_loop);
555
556   return default_main_context;
557 }
558
559 /* Hooks for adding to the main loop */
560
561 /**
562  * g_source_new:
563  * @source_funcs: structure containing functions that implement
564  *                the sources behavior.
565  * @struct_size: size of the #GSource structure to create.
566  * 
567  * Creates a new #GSource structure. The size is specified to
568  * allow creating structures derived from #GSource that contain
569  * additional data. The size passed in must be at least
570  * <literal>sizeof (GSource)</literal>.
571  * 
572  * The source will not initially be associated with any #GMainContext
573  * and must be added to one with g_source_attach() before it will be
574  * executed.
575  * 
576  * Return value: the newly-created #GSource.
577  **/
578 GSource *
579 g_source_new (GSourceFuncs *source_funcs,
580               guint         struct_size)
581 {
582   GSource *source;
583
584   g_return_val_if_fail (source_funcs != NULL, NULL);
585   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
586   
587   source = (GSource*) g_malloc0 (struct_size);
588
589   source->source_funcs = source_funcs;
590   source->ref_count = 1;
591   
592   source->priority = G_PRIORITY_DEFAULT;
593
594   source->flags = G_HOOK_FLAG_ACTIVE;
595
596   /* NULL/0 initialization for all other fields */
597   
598   return source;
599 }
600
601 /* Holds context's lock
602  */
603 static void
604 g_source_list_add (GSource      *source,
605                    GMainContext *context)
606 {
607   GSource *tmp_source, *last_source;
608   
609   last_source = NULL;
610   tmp_source = context->source_list;
611   while (tmp_source && tmp_source->priority <= source->priority)
612     {
613       last_source = tmp_source;
614       tmp_source = tmp_source->next;
615     }
616
617   source->next = tmp_source;
618   if (tmp_source)
619     tmp_source->prev = source;
620   
621   source->prev = last_source;
622   if (last_source)
623     last_source->next = source;
624   else
625     context->source_list = source;
626 }
627
628 /* Holds context's lock
629  */
630 static void
631 g_source_list_remove (GSource      *source,
632                       GMainContext *context)
633 {
634   if (source->prev)
635     source->prev->next = source->next;
636   else
637     context->source_list = source->next;
638
639   if (source->next)
640     source->next->prev = source->prev;
641
642   source->prev = NULL;
643   source->next = NULL;
644 }
645
646 /**
647  * g_source_attach:
648  * @source: a #GSource
649  * @context: a #GMainContext (if %NULL, the default context will be used)
650  * 
651  * Adds a #GSource to a @context so that it will be executed within
652  * that context. Remove it by calling g_source_destroy().
653  *
654  * Return value: the ID (greater than 0) for the source within the 
655  *   #GMainContext. 
656  **/
657 guint
658 g_source_attach (GSource      *source,
659                  GMainContext *context)
660 {
661   guint result = 0;
662   GSList *tmp_list;
663
664   g_return_val_if_fail (source->context == NULL, 0);
665   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
666   
667   if (!context)
668     context = g_main_context_default ();
669
670   LOCK_CONTEXT (context);
671
672   source->context = context;
673   result = source->source_id = context->next_id++;
674
675   source->ref_count++;
676   g_source_list_add (source, context);
677
678   tmp_list = source->poll_fds;
679   while (tmp_list)
680     {
681       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
682       tmp_list = tmp_list->next;
683     }
684
685 #ifdef G_THREADS_ENABLED
686   /* Now wake up the main loop if it is waiting in the poll() */
687   g_main_context_wakeup_unlocked (context);
688 #endif
689
690   UNLOCK_CONTEXT (context);
691
692   return result;
693 }
694
695 static void
696 g_source_destroy_internal (GSource      *source,
697                            GMainContext *context,
698                            gboolean      have_lock)
699 {
700   if (!have_lock)
701     LOCK_CONTEXT (context);
702   
703   if (!SOURCE_DESTROYED (source))
704     {
705       GSList *tmp_list;
706       gpointer old_cb_data;
707       GSourceCallbackFuncs *old_cb_funcs;
708       
709       source->flags &= ~G_HOOK_FLAG_ACTIVE;
710
711       old_cb_data = source->callback_data;
712       old_cb_funcs = source->callback_funcs;
713
714       source->callback_data = NULL;
715       source->callback_funcs = NULL;
716
717       if (old_cb_funcs)
718         {
719           UNLOCK_CONTEXT (context);
720           old_cb_funcs->unref (old_cb_data);
721           LOCK_CONTEXT (context);
722         }
723
724       if (!SOURCE_BLOCKED (source))
725         {
726           tmp_list = source->poll_fds;
727           while (tmp_list)
728             {
729               g_main_context_remove_poll_unlocked (context, tmp_list->data);
730               tmp_list = tmp_list->next;
731             }
732         }
733           
734       g_source_unref_internal (source, context, TRUE);
735     }
736
737   if (!have_lock)
738     UNLOCK_CONTEXT (context);
739 }
740
741 /**
742  * g_source_destroy:
743  * @source: a #GSource
744  * 
745  * Removes a source from its #GMainContext, if any, and mark it as
746  * destroyed.  The source cannot be subsequently added to another
747  * context.
748  **/
749 void
750 g_source_destroy (GSource *source)
751 {
752   GMainContext *context;
753   
754   g_return_if_fail (source != NULL);
755   
756   context = source->context;
757   
758   if (context)
759     g_source_destroy_internal (source, context, FALSE);
760   else
761     source->flags &= ~G_HOOK_FLAG_ACTIVE;
762 }
763
764 /**
765  * g_source_get_id:
766  * @source: a #GSource
767  * 
768  * Returns the numeric ID for a particular source. The ID of a source
769  * is a positive integer which is unique within a particular main loop 
770  * context. The reverse
771  * mapping from ID to source is done by g_main_context_find_source_by_id().
772  *
773  * Return value: the ID (greater than 0) for the source
774  **/
775 guint
776 g_source_get_id (GSource *source)
777 {
778   guint result;
779   
780   g_return_val_if_fail (source != NULL, 0);
781   g_return_val_if_fail (source->context != NULL, 0);
782
783   LOCK_CONTEXT (source->context);
784   result = source->source_id;
785   UNLOCK_CONTEXT (source->context);
786   
787   return result;
788 }
789
790 /**
791  * g_source_get_context:
792  * @source: a #GSource
793  * 
794  * Gets the #GMainContext with which the source is associated.
795  * Calling this function on a destroyed source is an error.
796  * 
797  * Return value: the #GMainContext with which the source is associated,
798  *               or %NULL if the context has not yet been added
799  *               to a source.
800  **/
801 GMainContext *
802 g_source_get_context (GSource *source)
803 {
804   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
805
806   return source->context;
807 }
808
809 /**
810  * g_source_add_poll:
811  * @source:a #GSource 
812  * @fd: a #GPollFD structure holding information about a file
813  *      descriptor to watch.
814  * 
815  * Adds a file descriptor to the set of file descriptors polled for
816  * this source. This is usually combined with g_source_new() to add an
817  * event source. The event source's check function will typically test
818  * the @revents field in the #GPollFD struct and return %TRUE if events need
819  * to be processed.
820  **/
821 void
822 g_source_add_poll (GSource *source,
823                    GPollFD *fd)
824 {
825   GMainContext *context;
826   
827   g_return_if_fail (source != NULL);
828   g_return_if_fail (fd != NULL);
829   g_return_if_fail (!SOURCE_DESTROYED (source));
830   
831   context = source->context;
832
833   if (context)
834     LOCK_CONTEXT (context);
835   
836   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
837
838   if (context)
839     {
840       if (!SOURCE_BLOCKED (source))
841         g_main_context_add_poll_unlocked (context, source->priority, fd);
842       UNLOCK_CONTEXT (context);
843     }
844 }
845
846 /**
847  * g_source_remove_poll:
848  * @source:a #GSource 
849  * @fd: a #GPollFD structure previously passed to g_source_add_poll().
850  * 
851  * Removes a file descriptor from the set of file descriptors polled for
852  * this source. 
853  **/
854 void
855 g_source_remove_poll (GSource *source,
856                       GPollFD *fd)
857 {
858   GMainContext *context;
859   
860   g_return_if_fail (source != NULL);
861   g_return_if_fail (fd != NULL);
862   g_return_if_fail (!SOURCE_DESTROYED (source));
863   
864   context = source->context;
865
866   if (context)
867     LOCK_CONTEXT (context);
868   
869   source->poll_fds = g_slist_remove (source->poll_fds, fd);
870
871   if (context)
872     {
873       if (!SOURCE_BLOCKED (source))
874         g_main_context_remove_poll_unlocked (context, fd);
875       UNLOCK_CONTEXT (context);
876     }
877 }
878
879 /**
880  * g_source_set_callback_indirect:
881  * @source: the source
882  * @callback_data: pointer to callback data "object"
883  * @callback_funcs: functions for reference counting @callback_data
884  *                  and getting the callback and data
885  * 
886  * Sets the callback function storing the data as a refcounted callback
887  * "object". This is used internally. Note that calling 
888  * g_source_set_callback_indirect() assumes
889  * an initial reference count on @callback_data, and thus
890  * @callback_funcs->unref will eventually be called once more
891  * than @callback_funcs->ref.
892  **/
893 void
894 g_source_set_callback_indirect (GSource              *source,
895                                 gpointer              callback_data,
896                                 GSourceCallbackFuncs *callback_funcs)
897 {
898   GMainContext *context;
899   gpointer old_cb_data;
900   GSourceCallbackFuncs *old_cb_funcs;
901   
902   g_return_if_fail (source != NULL);
903   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
904
905   context = source->context;
906
907   if (context)
908     LOCK_CONTEXT (context);
909
910   old_cb_data = source->callback_data;
911   old_cb_funcs = source->callback_funcs;
912
913   source->callback_data = callback_data;
914   source->callback_funcs = callback_funcs;
915   
916   if (context)
917     UNLOCK_CONTEXT (context);
918   
919   if (old_cb_funcs)
920     old_cb_funcs->unref (old_cb_data);
921 }
922
923 static void
924 g_source_callback_ref (gpointer cb_data)
925 {
926   GSourceCallback *callback = cb_data;
927
928   callback->ref_count++;
929 }
930
931
932 static void
933 g_source_callback_unref (gpointer cb_data)
934 {
935   GSourceCallback *callback = cb_data;
936
937   callback->ref_count--;
938   if (callback->ref_count == 0)
939     {
940       if (callback->notify)
941         callback->notify (callback->data);
942       g_free (callback);
943     }
944 }
945
946 static void
947 g_source_callback_get (gpointer     cb_data,
948                        GSource     *source, 
949                        GSourceFunc *func,
950                        gpointer    *data)
951 {
952   GSourceCallback *callback = cb_data;
953
954   *func = callback->func;
955   *data = callback->data;
956 }
957
958 static GSourceCallbackFuncs g_source_callback_funcs = {
959   g_source_callback_ref,
960   g_source_callback_unref,
961   g_source_callback_get,
962 };
963
964 /**
965  * g_source_set_callback:
966  * @source: the source
967  * @func: a callback function
968  * @data: the data to pass to callback function
969  * @notify: a function to call when @data is no longer in use, or %NULL.
970  * 
971  * Sets the callback function for a source. The callback for a source is
972  * called from the source's dispatch function.
973  *
974  * The exact type of @func depends on the type of source; ie. you
975  * should not count on @func being called with @data as its first
976  * parameter.
977  * 
978  * Typically, you won't use this function. Instead use functions specific
979  * to the type of source you are using.
980  **/
981 void
982 g_source_set_callback (GSource        *source,
983                        GSourceFunc     func,
984                        gpointer        data,
985                        GDestroyNotify  notify)
986 {
987   GSourceCallback *new_callback;
988
989   g_return_if_fail (source != NULL);
990
991   new_callback = g_new (GSourceCallback, 1);
992
993   new_callback->ref_count = 1;
994   new_callback->func = func;
995   new_callback->data = data;
996   new_callback->notify = notify;
997
998   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
999 }
1000
1001
1002 /**
1003  * g_source_set_funcs:
1004  * @source: a #GSource
1005  * @funcs: the new #GSourceFuncs
1006  * 
1007  * Sets the source functions (can be used to override 
1008  * default implementations) of an unattached source.
1009  * 
1010  * Since: 2.12
1011  */
1012 void
1013 g_source_set_funcs (GSource     *source,
1014                    GSourceFuncs *funcs)
1015 {
1016   g_return_if_fail (source != NULL);
1017   g_return_if_fail (source->context == NULL);
1018   g_return_if_fail (source->ref_count > 0);
1019   g_return_if_fail (funcs != NULL);
1020
1021   source->source_funcs = funcs;
1022 }
1023
1024 /**
1025  * g_source_set_priority:
1026  * @source: a #GSource
1027  * @priority: the new priority.
1028  * 
1029  * Sets the priority of a source. While the main loop is being
1030  * run, a source will be dispatched if it is ready to be dispatched and no sources 
1031  * at a higher (numerically smaller) priority are ready to be dispatched.
1032  **/
1033 void
1034 g_source_set_priority (GSource  *source,
1035                        gint      priority)
1036 {
1037   GSList *tmp_list;
1038   GMainContext *context;
1039   
1040   g_return_if_fail (source != NULL);
1041
1042   context = source->context;
1043
1044   if (context)
1045     LOCK_CONTEXT (context);
1046   
1047   source->priority = priority;
1048
1049   if (context)
1050     {
1051       /* Remove the source from the context's source and then
1052        * add it back so it is sorted in the correct plcae
1053        */
1054       g_source_list_remove (source, source->context);
1055       g_source_list_add (source, source->context);
1056
1057       if (!SOURCE_BLOCKED (source))
1058         {
1059           tmp_list = source->poll_fds;
1060           while (tmp_list)
1061             {
1062               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1063               g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1064               
1065               tmp_list = tmp_list->next;
1066             }
1067         }
1068       
1069       UNLOCK_CONTEXT (source->context);
1070     }
1071 }
1072
1073 /**
1074  * g_source_get_priority:
1075  * @source: a #GSource
1076  * 
1077  * Gets the priority of a source.
1078  * 
1079  * Return value: the priority of the source
1080  **/
1081 gint
1082 g_source_get_priority (GSource *source)
1083 {
1084   g_return_val_if_fail (source != NULL, 0);
1085
1086   return source->priority;
1087 }
1088
1089 /**
1090  * g_source_set_can_recurse:
1091  * @source: a #GSource
1092  * @can_recurse: whether recursion is allowed for this source
1093  * 
1094  * Sets whether a source can be called recursively. If @can_recurse is
1095  * %TRUE, then while the source is being dispatched then this source
1096  * will be processed normally. Otherwise, all processing of this
1097  * source is blocked until the dispatch function returns.
1098  **/
1099 void
1100 g_source_set_can_recurse (GSource  *source,
1101                           gboolean  can_recurse)
1102 {
1103   GMainContext *context;
1104   
1105   g_return_if_fail (source != NULL);
1106
1107   context = source->context;
1108
1109   if (context)
1110     LOCK_CONTEXT (context);
1111   
1112   if (can_recurse)
1113     source->flags |= G_SOURCE_CAN_RECURSE;
1114   else
1115     source->flags &= ~G_SOURCE_CAN_RECURSE;
1116
1117   if (context)
1118     UNLOCK_CONTEXT (context);
1119 }
1120
1121 /**
1122  * g_source_get_can_recurse:
1123  * @source: a #GSource
1124  * 
1125  * Checks whether a source is allowed to be called recursively.
1126  * see g_source_set_can_recurse().
1127  * 
1128  * Return value: whether recursion is allowed.
1129  **/
1130 gboolean
1131 g_source_get_can_recurse (GSource  *source)
1132 {
1133   g_return_val_if_fail (source != NULL, FALSE);
1134   
1135   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1136 }
1137
1138 /**
1139  * g_source_ref:
1140  * @source: a #GSource
1141  * 
1142  * Increases the reference count on a source by one.
1143  * 
1144  * Return value: @source
1145  **/
1146 GSource *
1147 g_source_ref (GSource *source)
1148 {
1149   GMainContext *context;
1150   
1151   g_return_val_if_fail (source != NULL, NULL);
1152
1153   context = source->context;
1154
1155   if (context)
1156     LOCK_CONTEXT (context);
1157
1158   source->ref_count++;
1159
1160   if (context)
1161     UNLOCK_CONTEXT (context);
1162
1163   return source;
1164 }
1165
1166 /* g_source_unref() but possible to call within context lock
1167  */
1168 static void
1169 g_source_unref_internal (GSource      *source,
1170                          GMainContext *context,
1171                          gboolean      have_lock)
1172 {
1173   gpointer old_cb_data = NULL;
1174   GSourceCallbackFuncs *old_cb_funcs = NULL;
1175
1176   g_return_if_fail (source != NULL);
1177   
1178   if (!have_lock && context)
1179     LOCK_CONTEXT (context);
1180
1181   source->ref_count--;
1182   if (source->ref_count == 0)
1183     {
1184       old_cb_data = source->callback_data;
1185       old_cb_funcs = source->callback_funcs;
1186
1187       source->callback_data = NULL;
1188       source->callback_funcs = NULL;
1189
1190       if (context && !SOURCE_DESTROYED (source))
1191         {
1192           g_warning (G_STRLOC ": ref_count == 0, but source is still attached to a context!");
1193           source->ref_count++;
1194         }
1195       else if (context)
1196         g_source_list_remove (source, context);
1197
1198       if (source->source_funcs->finalize)
1199         source->source_funcs->finalize (source);
1200       
1201       g_slist_free (source->poll_fds);
1202       source->poll_fds = NULL;
1203       g_free (source);
1204     }
1205   
1206   if (!have_lock && context)
1207     UNLOCK_CONTEXT (context);
1208
1209   if (old_cb_funcs)
1210     {
1211       if (have_lock)
1212         UNLOCK_CONTEXT (context);
1213       
1214       old_cb_funcs->unref (old_cb_data);
1215
1216       if (have_lock)
1217         LOCK_CONTEXT (context);
1218     }
1219 }
1220
1221 /**
1222  * g_source_unref:
1223  * @source: a #GSource
1224  * 
1225  * Decreases the reference count of a source by one. If the
1226  * resulting reference count is zero the source and associated
1227  * memory will be destroyed. 
1228  **/
1229 void
1230 g_source_unref (GSource *source)
1231 {
1232   g_return_if_fail (source != NULL);
1233
1234   g_source_unref_internal (source, source->context, FALSE);
1235 }
1236
1237 /**
1238  * g_main_context_find_source_by_id:
1239  * @context: a #GMainContext (if %NULL, the default context will be used)
1240  * @source_id: the source ID, as returned by g_source_get_id(). 
1241  * 
1242  * Finds a #GSource given a pair of context and ID.
1243  * 
1244  * Return value: the #GSource if found, otherwise, %NULL
1245  **/
1246 GSource *
1247 g_main_context_find_source_by_id (GMainContext *context,
1248                                   guint         source_id)
1249 {
1250   GSource *source;
1251   
1252   g_return_val_if_fail (source_id > 0, NULL);
1253
1254   if (context == NULL)
1255     context = g_main_context_default ();
1256   
1257   LOCK_CONTEXT (context);
1258   
1259   source = context->source_list;
1260   while (source)
1261     {
1262       if (!SOURCE_DESTROYED (source) &&
1263           source->source_id == source_id)
1264         break;
1265       source = source->next;
1266     }
1267
1268   UNLOCK_CONTEXT (context);
1269
1270   return source;
1271 }
1272
1273 /**
1274  * g_main_context_find_source_by_funcs_user_data:
1275  * @context: a #GMainContext (if %NULL, the default context will be used).
1276  * @funcs: the @source_funcs passed to g_source_new().
1277  * @user_data: the user data from the callback.
1278  * 
1279  * Finds a source with the given source functions and user data.  If
1280  * multiple sources exist with the same source function and user data,
1281  * the first one found will be returned.
1282  * 
1283  * Return value: the source, if one was found, otherwise %NULL
1284  **/
1285 GSource *
1286 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1287                                                GSourceFuncs *funcs,
1288                                                gpointer      user_data)
1289 {
1290   GSource *source;
1291   
1292   g_return_val_if_fail (funcs != NULL, NULL);
1293
1294   if (context == NULL)
1295     context = g_main_context_default ();
1296   
1297   LOCK_CONTEXT (context);
1298
1299   source = context->source_list;
1300   while (source)
1301     {
1302       if (!SOURCE_DESTROYED (source) &&
1303           source->source_funcs == funcs &&
1304           source->callback_funcs)
1305         {
1306           GSourceFunc callback;
1307           gpointer callback_data;
1308
1309           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1310           
1311           if (callback_data == user_data)
1312             break;
1313         }
1314       source = source->next;
1315     }
1316
1317   UNLOCK_CONTEXT (context);
1318
1319   return source;
1320 }
1321
1322 /**
1323  * g_main_context_find_source_by_user_data:
1324  * @context: a #GMainContext
1325  * @user_data: the user_data for the callback.
1326  * 
1327  * Finds a source with the given user data for the callback.  If
1328  * multiple sources exist with the same user data, the first
1329  * one found will be returned.
1330  * 
1331  * Return value: the source, if one was found, otherwise %NULL
1332  **/
1333 GSource *
1334 g_main_context_find_source_by_user_data (GMainContext *context,
1335                                          gpointer      user_data)
1336 {
1337   GSource *source;
1338   
1339   if (context == NULL)
1340     context = g_main_context_default ();
1341   
1342   LOCK_CONTEXT (context);
1343
1344   source = context->source_list;
1345   while (source)
1346     {
1347       if (!SOURCE_DESTROYED (source) &&
1348           source->callback_funcs)
1349         {
1350           GSourceFunc callback;
1351           gpointer callback_data = NULL;
1352
1353           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1354
1355           if (callback_data == user_data)
1356             break;
1357         }
1358       source = source->next;
1359     }
1360
1361   UNLOCK_CONTEXT (context);
1362
1363   return source;
1364 }
1365
1366 /**
1367  * g_source_remove:
1368  * @tag: the ID of the source to remove.
1369  * 
1370  * Removes the source with the given id from the default main context. 
1371  * The id of
1372  * a #GSource is given by g_source_get_id(), or will be returned by the
1373  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1374  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1375  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1376  *
1377  * See also g_source_destroy(). You must use g_source_destroy() for sources
1378  * added to a non-default main context.
1379  *
1380  * Return value: %TRUE if the source was found and removed.
1381  **/
1382 gboolean
1383 g_source_remove (guint tag)
1384 {
1385   GSource *source;
1386   
1387   g_return_val_if_fail (tag > 0, FALSE);
1388
1389   source = g_main_context_find_source_by_id (NULL, tag);
1390   if (source)
1391     g_source_destroy (source);
1392
1393   return source != NULL;
1394 }
1395
1396 /**
1397  * g_source_remove_by_user_data:
1398  * @user_data: the user_data for the callback.
1399  * 
1400  * Removes a source from the default main loop context given the user
1401  * data for the callback. If multiple sources exist with the same user
1402  * data, only one will be destroyed.
1403  * 
1404  * Return value: %TRUE if a source was found and removed. 
1405  **/
1406 gboolean
1407 g_source_remove_by_user_data (gpointer user_data)
1408 {
1409   GSource *source;
1410   
1411   source = g_main_context_find_source_by_user_data (NULL, user_data);
1412   if (source)
1413     {
1414       g_source_destroy (source);
1415       return TRUE;
1416     }
1417   else
1418     return FALSE;
1419 }
1420
1421 /**
1422  * g_source_remove_by_funcs_user_data:
1423  * @funcs: The @source_funcs passed to g_source_new()
1424  * @user_data: the user data for the callback
1425  * 
1426  * Removes a source from the default main loop context given the
1427  * source functions and user data. If multiple sources exist with the
1428  * same source functions and user data, only one will be destroyed.
1429  * 
1430  * Return value: %TRUE if a source was found and removed. 
1431  **/
1432 gboolean
1433 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1434                                     gpointer      user_data)
1435 {
1436   GSource *source;
1437
1438   g_return_val_if_fail (funcs != NULL, FALSE);
1439
1440   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1441   if (source)
1442     {
1443       g_source_destroy (source);
1444       return TRUE;
1445     }
1446   else
1447     return FALSE;
1448 }
1449
1450 /**
1451  * g_get_current_time:
1452  * @result: #GTimeVal structure in which to store current time.
1453  * 
1454  * Equivalent to the UNIX gettimeofday() function, but portable.
1455  **/
1456 void
1457 g_get_current_time (GTimeVal *result)
1458 {
1459 #ifndef G_OS_WIN32
1460   struct timeval r;
1461
1462   g_return_if_fail (result != NULL);
1463
1464   /*this is required on alpha, there the timeval structs are int's
1465     not longs and a cast only would fail horribly*/
1466   gettimeofday (&r, NULL);
1467   result->tv_sec = r.tv_sec;
1468   result->tv_usec = r.tv_usec;
1469 #else
1470   FILETIME ft;
1471   guint64 time64;
1472
1473   g_return_if_fail (result != NULL);
1474
1475   GetSystemTimeAsFileTime (&ft);
1476   memmove (&time64, &ft, sizeof (FILETIME));
1477
1478   /* Convert from 100s of nanoseconds since 1601-01-01
1479    * to Unix epoch. Yes, this is Y2038 unsafe.
1480    */
1481   time64 -= G_GINT64_CONSTANT (116444736000000000);
1482   time64 /= 10;
1483
1484   result->tv_sec = time64 / 1000000;
1485   result->tv_usec = time64 % 1000000;
1486 #endif
1487 }
1488
1489 static void
1490 g_main_dispatch_free (gpointer dispatch)
1491 {
1492   g_slice_free (GMainDispatch, dispatch);
1493 }
1494
1495 /* Running the main loop */
1496
1497 static GMainDispatch *
1498 get_dispatch (void)
1499 {
1500   static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1501   GMainDispatch *dispatch = g_static_private_get (&depth_private);
1502   if (!dispatch)
1503     {
1504       dispatch = g_slice_new0 (GMainDispatch);
1505       g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1506     }
1507
1508   return dispatch;
1509 }
1510
1511 /**
1512  * g_main_depth:
1513  *
1514  * Returns the depth of the stack of calls to
1515  * g_main_context_dispatch() on any #GMainContext in the current thread.
1516  *  That is, when called from the toplevel, it gives 0. When
1517  * called from within a callback from g_main_context_iteration()
1518  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
1519  * a callback to a recursive call to g_main_context_iterate(),
1520  * it returns 2. And so forth.
1521  *
1522  * This function is useful in a situation like the following:
1523  * Imagine an extremely simple "garbage collected" system.
1524  *
1525  * |[
1526  * static GList *free_list;
1527  * 
1528  * gpointer
1529  * allocate_memory (gsize size)
1530  * { 
1531  *   gpointer result = g_malloc (size);
1532  *   free_list = g_list_prepend (free_list, result);
1533  *   return result;
1534  * }
1535  * 
1536  * void
1537  * free_allocated_memory (void)
1538  * {
1539  *   GList *l;
1540  *   for (l = free_list; l; l = l->next);
1541  *     g_free (l->data);
1542  *   g_list_free (free_list);
1543  *   free_list = NULL;
1544  *  }
1545  * 
1546  * [...]
1547  * 
1548  * while (TRUE); 
1549  *  {
1550  *    g_main_context_iteration (NULL, TRUE);
1551  *    free_allocated_memory();
1552  *   }
1553  * ]|
1554  *
1555  * This works from an application, however, if you want to do the same
1556  * thing from a library, it gets more difficult, since you no longer
1557  * control the main loop. You might think you can simply use an idle
1558  * function to make the call to free_allocated_memory(), but that
1559  * doesn't work, since the idle function could be called from a
1560  * recursive callback. This can be fixed by using g_main_depth()
1561  *
1562  * |[
1563  * gpointer
1564  * allocate_memory (gsize size)
1565  * { 
1566  *   FreeListBlock *block = g_new (FreeListBlock, 1);
1567  *   block->mem = g_malloc (size);
1568  *   block->depth = g_main_depth ();   
1569  *   free_list = g_list_prepend (free_list, block);
1570  *   return block->mem;
1571  * }
1572  * 
1573  * void
1574  * free_allocated_memory (void)
1575  * {
1576  *   GList *l;
1577  *   
1578  *   int depth = g_main_depth ();
1579  *   for (l = free_list; l; );
1580  *     {
1581  *       GList *next = l->next;
1582  *       FreeListBlock *block = l->data;
1583  *       if (block->depth > depth)
1584  *         {
1585  *           g_free (block->mem);
1586  *           g_free (block);
1587  *           free_list = g_list_delete_link (free_list, l);
1588  *         }
1589  *               
1590  *       l = next;
1591  *     }
1592  *   }
1593  * ]|
1594  *
1595  * There is a temptation to use g_main_depth() to solve
1596  * problems with reentrancy. For instance, while waiting for data
1597  * to be received from the network in response to a menu item,
1598  * the menu item might be selected again. It might seem that
1599  * one could make the menu item's callback return immediately
1600  * and do nothing if g_main_depth() returns a value greater than 1.
1601  * However, this should be avoided since the user then sees selecting
1602  * the menu item do nothing. Furthermore, you'll find yourself adding
1603  * these checks all over your code, since there are doubtless many,
1604  * many things that the user could do. Instead, you can use the
1605  * following techniques:
1606  *
1607  * <orderedlist>
1608  *  <listitem>
1609  *   <para>
1610  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
1611  *     the user from interacting with elements while the main
1612  *     loop is recursing.
1613  *   </para>
1614  *  </listitem>
1615  *  <listitem>
1616  *   <para>
1617  *     Avoid main loop recursion in situations where you can't handle
1618  *     arbitrary  callbacks. Instead, structure your code so that you
1619  *     simply return to the main loop and then get called again when
1620  *     there is more work to do.
1621  *   </para>
1622  *  </listitem>
1623  * </orderedlist>
1624  * 
1625  * Return value: The main loop recursion level in the current thread
1626  **/
1627 int
1628 g_main_depth (void)
1629 {
1630   GMainDispatch *dispatch = get_dispatch ();
1631   return dispatch->depth;
1632 }
1633
1634 /**
1635  * g_main_current_source:
1636  *
1637  * Returns the currently firing source for this thread.
1638  * 
1639  * Return value: The currently firing source or %NULL.
1640  *
1641  * Since: 2.12
1642  */
1643 GSource *
1644 g_main_current_source (void)
1645 {
1646   GMainDispatch *dispatch = get_dispatch ();
1647   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1648 }
1649
1650 /**
1651  * g_source_is_destroyed:
1652  * @source: a #GSource
1653  *
1654  * Returns whether @source has been destroyed.
1655  *
1656  * This is important when you operate upon your objects 
1657  * from within idle handlers, but may have freed the object 
1658  * before the dispatch of your idle handler.
1659  *
1660  * |[
1661  * static gboolean 
1662  * idle_callback (gpointer data)
1663  * {
1664  *   SomeWidget *self = data;
1665  *    
1666  *   GDK_THREADS_ENTER (<!-- -->);
1667  *   /<!-- -->* do stuff with self *<!-- -->/
1668  *   self->idle_id = 0;
1669  *   GDK_THREADS_LEAVE (<!-- -->);
1670  *    
1671  *   return FALSE;
1672  * }
1673  *  
1674  * static void 
1675  * some_widget_do_stuff_later (SomeWidget *self)
1676  * {
1677  *   self->idle_id = g_idle_add (idle_callback, self);
1678  * }
1679  *  
1680  * static void 
1681  * some_widget_finalize (GObject *object)
1682  * {
1683  *   SomeWidget *self = SOME_WIDGET (object);
1684  *    
1685  *   if (self->idle_id)
1686  *     g_source_remove (self->idle_id);
1687  *    
1688  *   G_OBJECT_CLASS (parent_class)->finalize (object);
1689  * }
1690  * ]|
1691  *
1692  * This will fail in a multi-threaded application if the 
1693  * widget is destroyed before the idle handler fires due 
1694  * to the use after free in the callback. A solution, to 
1695  * this particular problem, is to check to if the source
1696  * has already been destroy within the callback.
1697  *
1698  * |[
1699  * static gboolean 
1700  * idle_callback (gpointer data)
1701  * {
1702  *   SomeWidget *self = data;
1703  *   
1704  *   GDK_THREADS_ENTER ();
1705  *   if (!g_source_is_destroyed (g_main_current_source ()))
1706  *     {
1707  *       /<!-- -->* do stuff with self *<!-- -->/
1708  *     }
1709  *   GDK_THREADS_LEAVE ();
1710  *   
1711  *   return FALSE;
1712  * }
1713  * ]|
1714  *
1715  * Return value: %TRUE if the source has been destroyed
1716  *
1717  * Since: 2.12
1718  */
1719 gboolean
1720 g_source_is_destroyed (GSource *source)
1721 {
1722   return SOURCE_DESTROYED (source);
1723 }
1724
1725
1726 /* Temporarily remove all this source's file descriptors from the
1727  * poll(), so that if data comes available for one of the file descriptors
1728  * we don't continually spin in the poll()
1729  */
1730 /* HOLDS: source->context's lock */
1731 static void
1732 block_source (GSource *source)
1733 {
1734   GSList *tmp_list;
1735
1736   g_return_if_fail (!SOURCE_BLOCKED (source));
1737
1738   tmp_list = source->poll_fds;
1739   while (tmp_list)
1740     {
1741       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1742       tmp_list = tmp_list->next;
1743     }
1744 }
1745
1746 /* HOLDS: source->context's lock */
1747 static void
1748 unblock_source (GSource *source)
1749 {
1750   GSList *tmp_list;
1751   
1752   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1753   g_return_if_fail (!SOURCE_DESTROYED (source));
1754   
1755   tmp_list = source->poll_fds;
1756   while (tmp_list)
1757     {
1758       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1759       tmp_list = tmp_list->next;
1760     }
1761 }
1762
1763 /* HOLDS: context's lock */
1764 static void
1765 g_main_dispatch (GMainContext *context)
1766 {
1767   GMainDispatch *current = get_dispatch ();
1768   guint i;
1769
1770   for (i = 0; i < context->pending_dispatches->len; i++)
1771     {
1772       GSource *source = context->pending_dispatches->pdata[i];
1773
1774       context->pending_dispatches->pdata[i] = NULL;
1775       g_assert (source);
1776
1777       source->flags &= ~G_SOURCE_READY;
1778
1779       if (!SOURCE_DESTROYED (source))
1780         {
1781           gboolean was_in_call;
1782           gpointer user_data = NULL;
1783           GSourceFunc callback = NULL;
1784           GSourceCallbackFuncs *cb_funcs;
1785           gpointer cb_data;
1786           gboolean need_destroy;
1787
1788           gboolean (*dispatch) (GSource *,
1789                                 GSourceFunc,
1790                                 gpointer);
1791           GSList current_source_link;
1792
1793           dispatch = source->source_funcs->dispatch;
1794           cb_funcs = source->callback_funcs;
1795           cb_data = source->callback_data;
1796
1797           if (cb_funcs)
1798             cb_funcs->ref (cb_data);
1799           
1800           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
1801             block_source (source);
1802           
1803           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
1804           source->flags |= G_HOOK_FLAG_IN_CALL;
1805
1806           if (cb_funcs)
1807             cb_funcs->get (cb_data, source, &callback, &user_data);
1808
1809           UNLOCK_CONTEXT (context);
1810
1811           current->depth++;
1812           /* The on-stack allocation of the GSList is unconventional, but
1813            * we know that the lifetime of the link is bounded to this
1814            * function as the link is kept in a thread specific list and
1815            * not manipulated outside of this function and its descendants.
1816            * Avoiding the overhead of a g_slist_alloc() is useful as many
1817            * applications do little more than dispatch events.
1818            *
1819            * This is a performance hack - do not revert to g_slist_prepend()!
1820            */
1821           current_source_link.data = source;
1822           current_source_link.next = current->dispatching_sources;
1823           current->dispatching_sources = &current_source_link;
1824           need_destroy = ! dispatch (source,
1825                                      callback,
1826                                      user_data);
1827           g_assert (current->dispatching_sources == &current_source_link);
1828           current->dispatching_sources = current_source_link.next;
1829           current->depth--;
1830           
1831           if (cb_funcs)
1832             cb_funcs->unref (cb_data);
1833
1834           LOCK_CONTEXT (context);
1835           
1836           if (!was_in_call)
1837             source->flags &= ~G_HOOK_FLAG_IN_CALL;
1838
1839           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
1840               !SOURCE_DESTROYED (source))
1841             unblock_source (source);
1842           
1843           /* Note: this depends on the fact that we can't switch
1844            * sources from one main context to another
1845            */
1846           if (need_destroy && !SOURCE_DESTROYED (source))
1847             {
1848               g_assert (source->context == context);
1849               g_source_destroy_internal (source, context, TRUE);
1850             }
1851         }
1852       
1853       SOURCE_UNREF (source, context);
1854     }
1855
1856   g_ptr_array_set_size (context->pending_dispatches, 0);
1857 }
1858
1859 /* Holds context's lock */
1860 static inline GSource *
1861 next_valid_source (GMainContext *context,
1862                    GSource      *source)
1863 {
1864   GSource *new_source = source ? source->next : context->source_list;
1865
1866   while (new_source)
1867     {
1868       if (!SOURCE_DESTROYED (new_source))
1869         {
1870           new_source->ref_count++;
1871           break;
1872         }
1873       
1874       new_source = new_source->next;
1875     }
1876
1877   if (source)
1878     SOURCE_UNREF (source, context);
1879           
1880   return new_source;
1881 }
1882
1883 /**
1884  * g_main_context_acquire:
1885  * @context: a #GMainContext
1886  * 
1887  * Tries to become the owner of the specified context.
1888  * If some other thread is the owner of the context,
1889  * returns %FALSE immediately. Ownership is properly
1890  * recursive: the owner can require ownership again
1891  * and will release ownership when g_main_context_release()
1892  * is called as many times as g_main_context_acquire().
1893  *
1894  * You must be the owner of a context before you
1895  * can call g_main_context_prepare(), g_main_context_query(),
1896  * g_main_context_check(), g_main_context_dispatch().
1897  * 
1898  * Return value: %TRUE if the operation succeeded, and
1899  *   this thread is now the owner of @context.
1900  **/
1901 gboolean 
1902 g_main_context_acquire (GMainContext *context)
1903 {
1904 #ifdef G_THREADS_ENABLED
1905   gboolean result = FALSE;
1906   GThread *self = G_THREAD_SELF;
1907
1908   if (context == NULL)
1909     context = g_main_context_default ();
1910   
1911   LOCK_CONTEXT (context);
1912
1913   if (!context->owner)
1914     {
1915       context->owner = self;
1916       g_assert (context->owner_count == 0);
1917     }
1918
1919   if (context->owner == self)
1920     {
1921       context->owner_count++;
1922       result = TRUE;
1923     }
1924
1925   UNLOCK_CONTEXT (context); 
1926   
1927   return result;
1928 #else /* !G_THREADS_ENABLED */
1929   return TRUE;
1930 #endif /* G_THREADS_ENABLED */
1931 }
1932
1933 /**
1934  * g_main_context_release:
1935  * @context: a #GMainContext
1936  * 
1937  * Releases ownership of a context previously acquired by this thread
1938  * with g_main_context_acquire(). If the context was acquired multiple
1939  * times, the ownership will be released only when g_main_context_release()
1940  * is called as many times as it was acquired.
1941  **/
1942 void
1943 g_main_context_release (GMainContext *context)
1944 {
1945 #ifdef G_THREADS_ENABLED
1946   if (context == NULL)
1947     context = g_main_context_default ();
1948   
1949   LOCK_CONTEXT (context);
1950
1951   context->owner_count--;
1952   if (context->owner_count == 0)
1953     {
1954       context->owner = NULL;
1955
1956       if (context->waiters)
1957         {
1958           GMainWaiter *waiter = context->waiters->data;
1959           gboolean loop_internal_waiter =
1960             (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
1961           context->waiters = g_slist_delete_link (context->waiters,
1962                                                   context->waiters);
1963           if (!loop_internal_waiter)
1964             g_mutex_lock (waiter->mutex);
1965           
1966           g_cond_signal (waiter->cond);
1967           
1968           if (!loop_internal_waiter)
1969             g_mutex_unlock (waiter->mutex);
1970         }
1971     }
1972
1973   UNLOCK_CONTEXT (context); 
1974 #endif /* G_THREADS_ENABLED */
1975 }
1976
1977 /**
1978  * g_main_context_wait:
1979  * @context: a #GMainContext
1980  * @cond: a condition variable
1981  * @mutex: a mutex, currently held
1982  * 
1983  * Tries to become the owner of the specified context,
1984  * as with g_main_context_acquire(). But if another thread
1985  * is the owner, atomically drop @mutex and wait on @cond until 
1986  * that owner releases ownership or until @cond is signaled, then
1987  * try again (once) to become the owner.
1988  * 
1989  * Return value: %TRUE if the operation succeeded, and
1990  *   this thread is now the owner of @context.
1991  **/
1992 gboolean
1993 g_main_context_wait (GMainContext *context,
1994                      GCond        *cond,
1995                      GMutex       *mutex)
1996 {
1997 #ifdef G_THREADS_ENABLED
1998   gboolean result = FALSE;
1999   GThread *self = G_THREAD_SELF;
2000   gboolean loop_internal_waiter;
2001   
2002   if (context == NULL)
2003     context = g_main_context_default ();
2004
2005   loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2006   
2007   if (!loop_internal_waiter)
2008     LOCK_CONTEXT (context);
2009
2010   if (context->owner && context->owner != self)
2011     {
2012       GMainWaiter waiter;
2013
2014       waiter.cond = cond;
2015       waiter.mutex = mutex;
2016
2017       context->waiters = g_slist_append (context->waiters, &waiter);
2018       
2019       if (!loop_internal_waiter)
2020         UNLOCK_CONTEXT (context);
2021       g_cond_wait (cond, mutex);
2022       if (!loop_internal_waiter)      
2023         LOCK_CONTEXT (context);
2024
2025       context->waiters = g_slist_remove (context->waiters, &waiter);
2026     }
2027
2028   if (!context->owner)
2029     {
2030       context->owner = self;
2031       g_assert (context->owner_count == 0);
2032     }
2033
2034   if (context->owner == self)
2035     {
2036       context->owner_count++;
2037       result = TRUE;
2038     }
2039
2040   if (!loop_internal_waiter)
2041     UNLOCK_CONTEXT (context); 
2042   
2043   return result;
2044 #else /* !G_THREADS_ENABLED */
2045   return TRUE;
2046 #endif /* G_THREADS_ENABLED */
2047 }
2048
2049 /**
2050  * g_main_context_prepare:
2051  * @context: a #GMainContext
2052  * @priority: location to store priority of highest priority
2053  *            source already ready.
2054  * 
2055  * Prepares to poll sources within a main loop. The resulting information
2056  * for polling is determined by calling g_main_context_query ().
2057  * 
2058  * Return value: %TRUE if some source is ready to be dispatched
2059  *               prior to polling.
2060  **/
2061 gboolean
2062 g_main_context_prepare (GMainContext *context,
2063                         gint         *priority)
2064 {
2065   gint i;
2066   gint n_ready = 0;
2067   gint current_priority = G_MAXINT;
2068   GSource *source;
2069
2070   if (context == NULL)
2071     context = g_main_context_default ();
2072   
2073   LOCK_CONTEXT (context);
2074
2075   context->time_is_current = FALSE;
2076
2077   if (context->in_check_or_prepare)
2078     {
2079       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2080                  "prepare() member.");
2081       UNLOCK_CONTEXT (context);
2082       return FALSE;
2083     }
2084
2085 #ifdef G_THREADS_ENABLED
2086   if (context->poll_waiting)
2087     {
2088       g_warning("g_main_context_prepare(): main loop already active in another thread");
2089       UNLOCK_CONTEXT (context);
2090       return FALSE;
2091     }
2092   
2093   context->poll_waiting = TRUE;
2094 #endif /* G_THREADS_ENABLED */
2095
2096 #if 0
2097   /* If recursing, finish up current dispatch, before starting over */
2098   if (context->pending_dispatches)
2099     {
2100       if (dispatch)
2101         g_main_dispatch (context, &current_time);
2102       
2103       UNLOCK_CONTEXT (context);
2104       return TRUE;
2105     }
2106 #endif
2107
2108   /* If recursing, clear list of pending dispatches */
2109
2110   for (i = 0; i < context->pending_dispatches->len; i++)
2111     {
2112       if (context->pending_dispatches->pdata[i])
2113         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2114     }
2115   g_ptr_array_set_size (context->pending_dispatches, 0);
2116   
2117   /* Prepare all sources */
2118
2119   context->timeout = -1;
2120   
2121   source = next_valid_source (context, NULL);
2122   while (source)
2123     {
2124       gint source_timeout = -1;
2125
2126       if ((n_ready > 0) && (source->priority > current_priority))
2127         {
2128           SOURCE_UNREF (source, context);
2129           break;
2130         }
2131       if (SOURCE_BLOCKED (source))
2132         goto next;
2133
2134       if (!(source->flags & G_SOURCE_READY))
2135         {
2136           gboolean result;
2137           gboolean (*prepare)  (GSource  *source, 
2138                                 gint     *timeout);
2139
2140           prepare = source->source_funcs->prepare;
2141           context->in_check_or_prepare++;
2142           UNLOCK_CONTEXT (context);
2143
2144           result = (*prepare) (source, &source_timeout);
2145
2146           LOCK_CONTEXT (context);
2147           context->in_check_or_prepare--;
2148
2149           if (result)
2150             source->flags |= G_SOURCE_READY;
2151         }
2152
2153       if (source->flags & G_SOURCE_READY)
2154         {
2155           n_ready++;
2156           current_priority = source->priority;
2157           context->timeout = 0;
2158         }
2159       
2160       if (source_timeout >= 0)
2161         {
2162           if (context->timeout < 0)
2163             context->timeout = source_timeout;
2164           else
2165             context->timeout = MIN (context->timeout, source_timeout);
2166         }
2167
2168     next:
2169       source = next_valid_source (context, source);
2170     }
2171
2172   UNLOCK_CONTEXT (context);
2173   
2174   if (priority)
2175     *priority = current_priority;
2176   
2177   return (n_ready > 0);
2178 }
2179
2180 /**
2181  * g_main_context_query:
2182  * @context: a #GMainContext
2183  * @max_priority: maximum priority source to check
2184  * @timeout_: location to store timeout to be used in polling
2185  * @fds: location to store #GPollFD records that need to be polled.
2186  * @n_fds: length of @fds.
2187  * 
2188  * Determines information necessary to poll this main loop.
2189  * 
2190  * Return value: the number of records actually stored in @fds,
2191  *   or, if more than @n_fds records need to be stored, the number
2192  *   of records that need to be stored.
2193  **/
2194 gint
2195 g_main_context_query (GMainContext *context,
2196                       gint          max_priority,
2197                       gint         *timeout,
2198                       GPollFD      *fds,
2199                       gint          n_fds)
2200 {
2201   gint n_poll;
2202   GPollRec *pollrec;
2203   
2204   LOCK_CONTEXT (context);
2205
2206   pollrec = context->poll_records;
2207   n_poll = 0;
2208   while (pollrec && max_priority >= pollrec->priority)
2209     {
2210       /* We need to include entries with fd->events == 0 in the array because
2211        * otherwise if the application changes fd->events behind our back and 
2212        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2213        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2214        * this API, but it occurs in practice.) */
2215       if (n_poll < n_fds)
2216         {
2217           fds[n_poll].fd = pollrec->fd->fd;
2218           /* In direct contradiction to the Unix98 spec, IRIX runs into
2219            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2220            * flags in the events field of the pollfd while it should
2221            * just ignoring them. So we mask them out here.
2222            */
2223           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2224           fds[n_poll].revents = 0;
2225         }
2226
2227       pollrec = pollrec->next;
2228       n_poll++;
2229     }
2230
2231 #ifdef G_THREADS_ENABLED
2232   context->poll_changed = FALSE;
2233 #endif
2234   
2235   if (timeout)
2236     {
2237       *timeout = context->timeout;
2238       if (*timeout != 0)
2239         context->time_is_current = FALSE;
2240     }
2241   
2242   UNLOCK_CONTEXT (context);
2243
2244   return n_poll;
2245 }
2246
2247 /**
2248  * g_main_context_check:
2249  * @context: a #GMainContext
2250  * @max_priority: the maximum numerical priority of sources to check
2251  * @fds: array of #GPollFD's that was passed to the last call to
2252  *       g_main_context_query()
2253  * @n_fds: return value of g_main_context_query()
2254  * 
2255  * Passes the results of polling back to the main loop.
2256  * 
2257  * Return value: %TRUE if some sources are ready to be dispatched.
2258  **/
2259 gboolean
2260 g_main_context_check (GMainContext *context,
2261                       gint          max_priority,
2262                       GPollFD      *fds,
2263                       gint          n_fds)
2264 {
2265   GSource *source;
2266   GPollRec *pollrec;
2267   gint n_ready = 0;
2268   gint i;
2269    
2270   LOCK_CONTEXT (context);
2271
2272   if (context->in_check_or_prepare)
2273     {
2274       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2275                  "prepare() member.");
2276       UNLOCK_CONTEXT (context);
2277       return FALSE;
2278     }
2279   
2280 #ifdef G_THREADS_ENABLED
2281   if (!context->poll_waiting)
2282     {
2283 #ifndef G_OS_WIN32
2284       gchar a;
2285       read (context->wake_up_pipe[0], &a, 1);
2286 #endif
2287     }
2288   else
2289     context->poll_waiting = FALSE;
2290
2291   /* If the set of poll file descriptors changed, bail out
2292    * and let the main loop rerun
2293    */
2294   if (context->poll_changed)
2295     {
2296       UNLOCK_CONTEXT (context);
2297       return FALSE;
2298     }
2299 #endif /* G_THREADS_ENABLED */
2300   
2301   pollrec = context->poll_records;
2302   i = 0;
2303   while (i < n_fds)
2304     {
2305       if (pollrec->fd->events)
2306         pollrec->fd->revents = fds[i].revents;
2307
2308       pollrec = pollrec->next;
2309       i++;
2310     }
2311
2312   source = next_valid_source (context, NULL);
2313   while (source)
2314     {
2315       if ((n_ready > 0) && (source->priority > max_priority))
2316         {
2317           SOURCE_UNREF (source, context);
2318           break;
2319         }
2320       if (SOURCE_BLOCKED (source))
2321         goto next;
2322
2323       if (!(source->flags & G_SOURCE_READY))
2324         {
2325           gboolean result;
2326           gboolean (*check) (GSource  *source);
2327
2328           check = source->source_funcs->check;
2329           
2330           context->in_check_or_prepare++;
2331           UNLOCK_CONTEXT (context);
2332           
2333           result = (*check) (source);
2334           
2335           LOCK_CONTEXT (context);
2336           context->in_check_or_prepare--;
2337           
2338           if (result)
2339             source->flags |= G_SOURCE_READY;
2340         }
2341
2342       if (source->flags & G_SOURCE_READY)
2343         {
2344           source->ref_count++;
2345           g_ptr_array_add (context->pending_dispatches, source);
2346
2347           n_ready++;
2348
2349           /* never dispatch sources with less priority than the first
2350            * one we choose to dispatch
2351            */
2352           max_priority = source->priority;
2353         }
2354
2355     next:
2356       source = next_valid_source (context, source);
2357     }
2358
2359   UNLOCK_CONTEXT (context);
2360
2361   return n_ready > 0;
2362 }
2363
2364 /**
2365  * g_main_context_dispatch:
2366  * @context: a #GMainContext
2367  * 
2368  * Dispatches all pending sources.
2369  **/
2370 void
2371 g_main_context_dispatch (GMainContext *context)
2372 {
2373   LOCK_CONTEXT (context);
2374
2375   if (context->pending_dispatches->len > 0)
2376     {
2377       g_main_dispatch (context);
2378     }
2379
2380   UNLOCK_CONTEXT (context);
2381 }
2382
2383 /* HOLDS context lock */
2384 static gboolean
2385 g_main_context_iterate (GMainContext *context,
2386                         gboolean      block,
2387                         gboolean      dispatch,
2388                         GThread      *self)
2389 {
2390   gint max_priority;
2391   gint timeout;
2392   gboolean some_ready;
2393   gint nfds, allocated_nfds;
2394   GPollFD *fds = NULL;
2395
2396   UNLOCK_CONTEXT (context);
2397
2398 #ifdef G_THREADS_ENABLED
2399   if (!g_main_context_acquire (context))
2400     {
2401       gboolean got_ownership;
2402
2403       LOCK_CONTEXT (context);
2404
2405       g_return_val_if_fail (g_thread_supported (), FALSE);
2406
2407       if (!block)
2408         return FALSE;
2409
2410       if (!context->cond)
2411         context->cond = g_cond_new ();
2412
2413       got_ownership = g_main_context_wait (context,
2414                                            context->cond,
2415                                            g_static_mutex_get_mutex (&context->mutex));
2416
2417       if (!got_ownership)
2418         return FALSE;
2419     }
2420   else
2421     LOCK_CONTEXT (context);
2422 #endif /* G_THREADS_ENABLED */
2423   
2424   if (!context->cached_poll_array)
2425     {
2426       context->cached_poll_array_size = context->n_poll_records;
2427       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2428     }
2429
2430   allocated_nfds = context->cached_poll_array_size;
2431   fds = context->cached_poll_array;
2432   
2433   UNLOCK_CONTEXT (context);
2434
2435   g_main_context_prepare (context, &max_priority); 
2436   
2437   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2438                                        allocated_nfds)) > allocated_nfds)
2439     {
2440       LOCK_CONTEXT (context);
2441       g_free (fds);
2442       context->cached_poll_array_size = allocated_nfds = nfds;
2443       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2444       UNLOCK_CONTEXT (context);
2445     }
2446
2447   if (!block)
2448     timeout = 0;
2449   
2450   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2451   
2452   some_ready = g_main_context_check (context, max_priority, fds, nfds);
2453   
2454   if (dispatch)
2455     g_main_context_dispatch (context);
2456   
2457 #ifdef G_THREADS_ENABLED
2458   g_main_context_release (context);
2459 #endif /* G_THREADS_ENABLED */    
2460
2461   LOCK_CONTEXT (context);
2462
2463   return some_ready;
2464 }
2465
2466 /**
2467  * g_main_context_pending:
2468  * @context: a #GMainContext (if %NULL, the default context will be used)
2469  *
2470  * Checks if any sources have pending events for the given context.
2471  * 
2472  * Return value: %TRUE if events are pending.
2473  **/
2474 gboolean 
2475 g_main_context_pending (GMainContext *context)
2476 {
2477   gboolean retval;
2478
2479   if (!context)
2480     context = g_main_context_default();
2481
2482   LOCK_CONTEXT (context);
2483   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2484   UNLOCK_CONTEXT (context);
2485   
2486   return retval;
2487 }
2488
2489 /**
2490  * g_main_context_iteration:
2491  * @context: a #GMainContext (if %NULL, the default context will be used) 
2492  * @may_block: whether the call may block.
2493  * 
2494  * Runs a single iteration for the given main loop. This involves
2495  * checking to see if any event sources are ready to be processed,
2496  * then if no events sources are ready and @may_block is %TRUE, waiting
2497  * for a source to become ready, then dispatching the highest priority
2498  * events sources that are ready. Otherwise, if @may_block is %FALSE 
2499  * sources are not waited to become ready, only those highest priority 
2500  * events sources will be dispatched (if any), that are ready at this 
2501  * given moment without further waiting.
2502  *
2503  * Note that even when @may_block is %TRUE, it is still possible for 
2504  * g_main_context_iteration() to return %FALSE, since the the wait may 
2505  * be interrupted for other reasons than an event source becoming ready.
2506  * 
2507  * Return value: %TRUE if events were dispatched.
2508  **/
2509 gboolean
2510 g_main_context_iteration (GMainContext *context, gboolean may_block)
2511 {
2512   gboolean retval;
2513
2514   if (!context)
2515     context = g_main_context_default();
2516   
2517   LOCK_CONTEXT (context);
2518   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2519   UNLOCK_CONTEXT (context);
2520   
2521   return retval;
2522 }
2523
2524 /**
2525  * g_main_loop_new:
2526  * @context: a #GMainContext  (if %NULL, the default context will be used).
2527  * @is_running: set to %TRUE to indicate that the loop is running. This
2528  * is not very important since calling g_main_loop_run() will set this to
2529  * %TRUE anyway.
2530  * 
2531  * Creates a new #GMainLoop structure.
2532  * 
2533  * Return value: a new #GMainLoop.
2534  **/
2535 GMainLoop *
2536 g_main_loop_new (GMainContext *context,
2537                  gboolean      is_running)
2538 {
2539   GMainLoop *loop;
2540
2541   if (!context)
2542     context = g_main_context_default();
2543   
2544   g_main_context_ref (context);
2545
2546   loop = g_new0 (GMainLoop, 1);
2547   loop->context = context;
2548   loop->is_running = is_running != FALSE;
2549   loop->ref_count = 1;
2550   
2551   return loop;
2552 }
2553
2554 /**
2555  * g_main_loop_ref:
2556  * @loop: a #GMainLoop
2557  * 
2558  * Increases the reference count on a #GMainLoop object by one.
2559  * 
2560  * Return value: @loop
2561  **/
2562 GMainLoop *
2563 g_main_loop_ref (GMainLoop *loop)
2564 {
2565   g_return_val_if_fail (loop != NULL, NULL);
2566   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2567
2568   g_atomic_int_inc (&loop->ref_count);
2569
2570   return loop;
2571 }
2572
2573 /**
2574  * g_main_loop_unref:
2575  * @loop: a #GMainLoop
2576  * 
2577  * Decreases the reference count on a #GMainLoop object by one. If
2578  * the result is zero, free the loop and free all associated memory.
2579  **/
2580 void
2581 g_main_loop_unref (GMainLoop *loop)
2582 {
2583   g_return_if_fail (loop != NULL);
2584   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2585
2586   if (!g_atomic_int_dec_and_test (&loop->ref_count))
2587     return;
2588
2589   g_main_context_unref (loop->context);
2590   g_free (loop);
2591 }
2592
2593 /**
2594  * g_main_loop_run:
2595  * @loop: a #GMainLoop
2596  * 
2597  * Runs a main loop until g_main_loop_quit() is called on the loop.
2598  * If this is called for the thread of the loop's #GMainContext,
2599  * it will process events from the loop, otherwise it will
2600  * simply wait.
2601  **/
2602 void 
2603 g_main_loop_run (GMainLoop *loop)
2604 {
2605   GThread *self = G_THREAD_SELF;
2606
2607   g_return_if_fail (loop != NULL);
2608   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2609
2610 #ifdef G_THREADS_ENABLED
2611   if (!g_main_context_acquire (loop->context))
2612     {
2613       gboolean got_ownership = FALSE;
2614       
2615       /* Another thread owns this context */
2616       if (!g_thread_supported ())
2617         {
2618           g_warning ("g_main_loop_run() was called from second thread but "
2619                      "g_thread_init() was never called.");
2620           return;
2621         }
2622       
2623       LOCK_CONTEXT (loop->context);
2624
2625       g_atomic_int_inc (&loop->ref_count);
2626
2627       if (!loop->is_running)
2628         loop->is_running = TRUE;
2629
2630       if (!loop->context->cond)
2631         loop->context->cond = g_cond_new ();
2632           
2633       while (loop->is_running && !got_ownership)
2634         got_ownership = g_main_context_wait (loop->context,
2635                                              loop->context->cond,
2636                                              g_static_mutex_get_mutex (&loop->context->mutex));
2637       
2638       if (!loop->is_running)
2639         {
2640           UNLOCK_CONTEXT (loop->context);
2641           if (got_ownership)
2642             g_main_context_release (loop->context);
2643           g_main_loop_unref (loop);
2644           return;
2645         }
2646
2647       g_assert (got_ownership);
2648     }
2649   else
2650     LOCK_CONTEXT (loop->context);
2651 #endif /* G_THREADS_ENABLED */ 
2652
2653   if (loop->context->in_check_or_prepare)
2654     {
2655       g_warning ("g_main_loop_run(): called recursively from within a source's "
2656                  "check() or prepare() member, iteration not possible.");
2657       return;
2658     }
2659
2660   g_atomic_int_inc (&loop->ref_count);
2661   loop->is_running = TRUE;
2662   while (loop->is_running)
2663     g_main_context_iterate (loop->context, TRUE, TRUE, self);
2664
2665   UNLOCK_CONTEXT (loop->context);
2666   
2667 #ifdef G_THREADS_ENABLED
2668   g_main_context_release (loop->context);
2669 #endif /* G_THREADS_ENABLED */    
2670   
2671   g_main_loop_unref (loop);
2672 }
2673
2674 /**
2675  * g_main_loop_quit:
2676  * @loop: a #GMainLoop
2677  * 
2678  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2679  * for the loop will return. 
2680  *
2681  * Note that sources that have already been dispatched when 
2682  * g_main_loop_quit() is called will still be executed.
2683  **/
2684 void 
2685 g_main_loop_quit (GMainLoop *loop)
2686 {
2687   g_return_if_fail (loop != NULL);
2688   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2689
2690   LOCK_CONTEXT (loop->context);
2691   loop->is_running = FALSE;
2692   g_main_context_wakeup_unlocked (loop->context);
2693
2694 #ifdef G_THREADS_ENABLED
2695   if (loop->context->cond)
2696     g_cond_broadcast (loop->context->cond);
2697 #endif /* G_THREADS_ENABLED */
2698
2699   UNLOCK_CONTEXT (loop->context);
2700 }
2701
2702 /**
2703  * g_main_loop_is_running:
2704  * @loop: a #GMainLoop.
2705  * 
2706  * Checks to see if the main loop is currently being run via g_main_loop_run().
2707  * 
2708  * Return value: %TRUE if the mainloop is currently being run.
2709  **/
2710 gboolean
2711 g_main_loop_is_running (GMainLoop *loop)
2712 {
2713   g_return_val_if_fail (loop != NULL, FALSE);
2714   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2715
2716   return loop->is_running;
2717 }
2718
2719 /**
2720  * g_main_loop_get_context:
2721  * @loop: a #GMainLoop.
2722  * 
2723  * Returns the #GMainContext of @loop.
2724  * 
2725  * Return value: the #GMainContext of @loop
2726  **/
2727 GMainContext *
2728 g_main_loop_get_context (GMainLoop *loop)
2729 {
2730   g_return_val_if_fail (loop != NULL, NULL);
2731   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2732  
2733   return loop->context;
2734 }
2735
2736 /* HOLDS: context's lock */
2737 static void
2738 g_main_context_poll (GMainContext *context,
2739                      gint          timeout,
2740                      gint          priority,
2741                      GPollFD      *fds,
2742                      gint          n_fds)
2743 {
2744 #ifdef  G_MAIN_POLL_DEBUG
2745   GTimer *poll_timer;
2746   GPollRec *pollrec;
2747   gint i;
2748 #endif
2749
2750   GPollFunc poll_func;
2751
2752   if (n_fds || timeout != 0)
2753     {
2754 #ifdef  G_MAIN_POLL_DEBUG
2755       if (_g_main_poll_debug)
2756         {
2757           g_print ("polling context=%p n=%d timeout=%d\n",
2758                    context, n_fds, timeout);
2759           poll_timer = g_timer_new ();
2760         }
2761 #endif
2762
2763       LOCK_CONTEXT (context);
2764
2765       poll_func = context->poll_func;
2766       
2767       UNLOCK_CONTEXT (context);
2768       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2769         {
2770 #ifndef G_OS_WIN32
2771           g_warning ("poll(2) failed due to: %s.",
2772                      g_strerror (errno));
2773 #else
2774           /* If g_poll () returns -1, it has already called g_warning() */
2775 #endif
2776         }
2777       
2778 #ifdef  G_MAIN_POLL_DEBUG
2779       if (_g_main_poll_debug)
2780         {
2781           LOCK_CONTEXT (context);
2782
2783           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
2784                    n_fds,
2785                    timeout,
2786                    g_timer_elapsed (poll_timer, NULL));
2787           g_timer_destroy (poll_timer);
2788           pollrec = context->poll_records;
2789
2790           while (pollrec != NULL)
2791             {
2792               i = 0;
2793               while (i < n_fds)
2794                 {
2795                   if (fds[i].fd == pollrec->fd->fd &&
2796                       pollrec->fd->events &&
2797                       fds[i].revents)
2798                     {
2799                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
2800                       if (fds[i].revents & G_IO_IN)
2801                         g_print ("i");
2802                       if (fds[i].revents & G_IO_OUT)
2803                         g_print ("o");
2804                       if (fds[i].revents & G_IO_PRI)
2805                         g_print ("p");
2806                       if (fds[i].revents & G_IO_ERR)
2807                         g_print ("e");
2808                       if (fds[i].revents & G_IO_HUP)
2809                         g_print ("h");
2810                       if (fds[i].revents & G_IO_NVAL)
2811                         g_print ("n");
2812                       g_print ("]");
2813                     }
2814                   i++;
2815                 }
2816               pollrec = pollrec->next;
2817             }
2818           g_print ("\n");
2819
2820           UNLOCK_CONTEXT (context);
2821         }
2822 #endif
2823     } /* if (n_fds || timeout != 0) */
2824 }
2825
2826 /**
2827  * g_main_context_add_poll:
2828  * @context: a #GMainContext (or %NULL for the default context)
2829  * @fd: a #GPollFD structure holding information about a file
2830  *      descriptor to watch.
2831  * @priority: the priority for this file descriptor which should be
2832  *      the same as the priority used for g_source_attach() to ensure that the
2833  *      file descriptor is polled whenever the results may be needed.
2834  * 
2835  * Adds a file descriptor to the set of file descriptors polled for
2836  * this context. This will very seldomly be used directly. Instead
2837  * a typical event source will use g_source_add_poll() instead.
2838  **/
2839 void
2840 g_main_context_add_poll (GMainContext *context,
2841                          GPollFD      *fd,
2842                          gint          priority)
2843 {
2844   if (!context)
2845     context = g_main_context_default ();
2846   
2847   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2848   g_return_if_fail (fd);
2849
2850   LOCK_CONTEXT (context);
2851   g_main_context_add_poll_unlocked (context, priority, fd);
2852   UNLOCK_CONTEXT (context);
2853 }
2854
2855 /* HOLDS: main_loop_lock */
2856 static void 
2857 g_main_context_add_poll_unlocked (GMainContext *context,
2858                                   gint          priority,
2859                                   GPollFD      *fd)
2860 {
2861   GPollRec *lastrec, *pollrec;
2862   GPollRec *newrec = g_slice_new (GPollRec);
2863
2864   /* This file descriptor may be checked before we ever poll */
2865   fd->revents = 0;
2866   newrec->fd = fd;
2867   newrec->priority = priority;
2868
2869   lastrec = NULL;
2870   pollrec = context->poll_records;
2871   while (pollrec && priority >= pollrec->priority)
2872     {
2873       lastrec = pollrec;
2874       pollrec = pollrec->next;
2875     }
2876   
2877   if (lastrec)
2878     lastrec->next = newrec;
2879   else
2880     context->poll_records = newrec;
2881
2882   newrec->next = pollrec;
2883
2884   context->n_poll_records++;
2885
2886 #ifdef G_THREADS_ENABLED
2887   context->poll_changed = TRUE;
2888
2889   /* Now wake up the main loop if it is waiting in the poll() */
2890   g_main_context_wakeup_unlocked (context);
2891 #endif
2892 }
2893
2894 /**
2895  * g_main_context_remove_poll:
2896  * @context:a #GMainContext 
2897  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
2898  * 
2899  * Removes file descriptor from the set of file descriptors to be
2900  * polled for a particular context.
2901  **/
2902 void
2903 g_main_context_remove_poll (GMainContext *context,
2904                             GPollFD      *fd)
2905 {
2906   if (!context)
2907     context = g_main_context_default ();
2908   
2909   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
2910   g_return_if_fail (fd);
2911
2912   LOCK_CONTEXT (context);
2913   g_main_context_remove_poll_unlocked (context, fd);
2914   UNLOCK_CONTEXT (context);
2915 }
2916
2917 static void
2918 g_main_context_remove_poll_unlocked (GMainContext *context,
2919                                      GPollFD      *fd)
2920 {
2921   GPollRec *pollrec, *lastrec;
2922
2923   lastrec = NULL;
2924   pollrec = context->poll_records;
2925
2926   while (pollrec)
2927     {
2928       if (pollrec->fd == fd)
2929         {
2930           if (lastrec != NULL)
2931             lastrec->next = pollrec->next;
2932           else
2933             context->poll_records = pollrec->next;
2934
2935           g_slice_free (GPollRec, pollrec);
2936
2937           context->n_poll_records--;
2938           break;
2939         }
2940       lastrec = pollrec;
2941       pollrec = pollrec->next;
2942     }
2943
2944 #ifdef G_THREADS_ENABLED
2945   context->poll_changed = TRUE;
2946   
2947   /* Now wake up the main loop if it is waiting in the poll() */
2948   g_main_context_wakeup_unlocked (context);
2949 #endif
2950 }
2951
2952 /**
2953  * g_source_get_current_time:
2954  * @source:  a #GSource
2955  * @timeval: #GTimeVal structure in which to store current time.
2956  * 
2957  * Gets the "current time" to be used when checking 
2958  * this source. The advantage of calling this function over
2959  * calling g_get_current_time() directly is that when 
2960  * checking multiple sources, GLib can cache a single value
2961  * instead of having to repeatedly get the system time.
2962  **/
2963 void
2964 g_source_get_current_time (GSource  *source,
2965                            GTimeVal *timeval)
2966 {
2967   GMainContext *context;
2968   
2969   g_return_if_fail (source->context != NULL);
2970  
2971   context = source->context;
2972
2973   LOCK_CONTEXT (context);
2974
2975   if (!context->time_is_current)
2976     {
2977       g_get_current_time (&context->current_time);
2978       context->time_is_current = TRUE;
2979     }
2980   
2981   *timeval = context->current_time;
2982   
2983   UNLOCK_CONTEXT (context);
2984 }
2985
2986 /**
2987  * g_main_context_set_poll_func:
2988  * @context: a #GMainContext
2989  * @func: the function to call to poll all file descriptors
2990  * 
2991  * Sets the function to use to handle polling of file descriptors. It
2992  * will be used instead of the poll() system call 
2993  * (or GLib's replacement function, which is used where 
2994  * poll() isn't available).
2995  *
2996  * This function could possibly be used to integrate the GLib event
2997  * loop with an external event loop.
2998  **/
2999 void
3000 g_main_context_set_poll_func (GMainContext *context,
3001                               GPollFunc     func)
3002 {
3003   if (!context)
3004     context = g_main_context_default ();
3005   
3006   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3007
3008   LOCK_CONTEXT (context);
3009   
3010   if (func)
3011     context->poll_func = func;
3012   else
3013     context->poll_func = g_poll;
3014
3015   UNLOCK_CONTEXT (context);
3016 }
3017
3018 /**
3019  * g_main_context_get_poll_func:
3020  * @context: a #GMainContext
3021  * 
3022  * Gets the poll function set by g_main_context_set_poll_func().
3023  * 
3024  * Return value: the poll function
3025  **/
3026 GPollFunc
3027 g_main_context_get_poll_func (GMainContext *context)
3028 {
3029   GPollFunc result;
3030   
3031   if (!context)
3032     context = g_main_context_default ();
3033   
3034   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3035
3036   LOCK_CONTEXT (context);
3037   result = context->poll_func;
3038   UNLOCK_CONTEXT (context);
3039
3040   return result;
3041 }
3042
3043 /* HOLDS: context's lock */
3044 /* Wake the main loop up from a poll() */
3045 static void
3046 g_main_context_wakeup_unlocked (GMainContext *context)
3047 {
3048 #ifdef G_THREADS_ENABLED
3049   if (g_thread_supported() && context->poll_waiting)
3050     {
3051       context->poll_waiting = FALSE;
3052 #ifndef G_OS_WIN32
3053       write (context->wake_up_pipe[1], "A", 1);
3054 #else
3055       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3056 #endif
3057     }
3058 #endif
3059 }
3060
3061 /**
3062  * g_main_context_wakeup:
3063  * @context: a #GMainContext
3064  * 
3065  * If @context is currently waiting in a poll(), interrupt
3066  * the poll(), and continue the iteration process.
3067  **/
3068 void
3069 g_main_context_wakeup (GMainContext *context)
3070 {
3071   if (!context)
3072     context = g_main_context_default ();
3073   
3074   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3075
3076   LOCK_CONTEXT (context);
3077   g_main_context_wakeup_unlocked (context);
3078   UNLOCK_CONTEXT (context);
3079 }
3080
3081 /**
3082  * g_main_context_is_owner:
3083  * @context: a #GMainContext
3084  * 
3085  * Determines whether this thread holds the (recursive)
3086  * ownership of this #GMaincontext. This is useful to
3087  * know before waiting on another thread that may be
3088  * blocking to get ownership of @context.
3089  *
3090  * Returns: %TRUE if current thread is owner of @context.
3091  *
3092  * Since: 2.10
3093  **/
3094 gboolean
3095 g_main_context_is_owner (GMainContext *context)
3096 {
3097   gboolean is_owner;
3098
3099   if (!context)
3100     context = g_main_context_default ();
3101
3102 #ifdef G_THREADS_ENABLED
3103   LOCK_CONTEXT (context);
3104   is_owner = context->owner == G_THREAD_SELF;
3105   UNLOCK_CONTEXT (context);
3106 #else
3107   is_owner = TRUE;
3108 #endif
3109
3110   return is_owner;
3111 }
3112
3113 /* Timeouts */
3114
3115 static void
3116 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3117                           GTimeVal       *current_time)
3118 {
3119   guint seconds = timeout_source->interval / 1000;
3120   guint msecs = timeout_source->interval - seconds * 1000;
3121
3122   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3123   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3124   if (timeout_source->expiration.tv_usec >= 1000000)
3125     {
3126       timeout_source->expiration.tv_usec -= 1000000;
3127       timeout_source->expiration.tv_sec++;
3128     }
3129   if (timer_perturb==-1)
3130     {
3131       /*
3132        * we want a per machine/session unique 'random' value; try the dbus
3133        * address first, that has a UUID in it. If there is no dbus, use the
3134        * hostname for hashing.
3135        */
3136       const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3137       if (!session_bus_address)
3138         session_bus_address = g_getenv ("HOSTNAME");
3139       if (session_bus_address)
3140         timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3141       else
3142         timer_perturb = 0;
3143     }
3144   if (timeout_source->granularity)
3145     {
3146       gint remainder;
3147       gint gran; /* in usecs */
3148       gint perturb;
3149
3150       gran = timeout_source->granularity * 1000;
3151       perturb = timer_perturb % gran;
3152       /*
3153        * We want to give each machine a per machine pertubation;
3154        * shift time back first, and forward later after the rounding
3155        */
3156
3157       timeout_source->expiration.tv_usec -= perturb;
3158       if (timeout_source->expiration.tv_usec < 0)
3159         {
3160           timeout_source->expiration.tv_usec += 1000000;
3161           timeout_source->expiration.tv_sec--;
3162         }
3163
3164       remainder = timeout_source->expiration.tv_usec % gran;
3165       if (remainder >= gran/4) /* round up */
3166         timeout_source->expiration.tv_usec += gran;
3167       timeout_source->expiration.tv_usec -= remainder;
3168       /* shift back */
3169       timeout_source->expiration.tv_usec += perturb;
3170
3171       /* the rounding may have overflown tv_usec */
3172       while (timeout_source->expiration.tv_usec > 1000000)
3173         {
3174           timeout_source->expiration.tv_usec -= 1000000;
3175           timeout_source->expiration.tv_sec++;
3176         }
3177     }
3178 }
3179
3180 static gboolean
3181 g_timeout_prepare (GSource *source,
3182                    gint    *timeout)
3183 {
3184   glong sec;
3185   glong msec;
3186   GTimeVal current_time;
3187   
3188   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3189
3190   g_source_get_current_time (source, &current_time);
3191
3192   sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3193   msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3194
3195   /* We do the following in a rather convoluted fashion to deal with
3196    * the fact that we don't have an integral type big enough to hold
3197    * the difference of two timevals in millseconds.
3198    */
3199   if (sec < 0 || (sec == 0 && msec < 0))
3200     msec = 0;
3201   else
3202     {
3203       glong interval_sec = timeout_source->interval / 1000;
3204       glong interval_msec = timeout_source->interval % 1000;
3205
3206       if (msec < 0)
3207         {
3208           msec += 1000;
3209           sec -= 1;
3210         }
3211       
3212       if (sec > interval_sec ||
3213           (sec == interval_sec && msec > interval_msec))
3214         {
3215           /* The system time has been set backwards, so we
3216            * reset the expiration time to now + timeout_source->interval;
3217            * this at least avoids hanging for long periods of time.
3218            */
3219           g_timeout_set_expiration (timeout_source, &current_time);
3220           msec = MIN (G_MAXINT, timeout_source->interval);
3221         }
3222       else
3223         {
3224           msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3225         }
3226     }
3227
3228   *timeout = (gint)msec;
3229   
3230   return msec == 0;
3231 }
3232
3233 static gboolean 
3234 g_timeout_check (GSource *source)
3235 {
3236   GTimeVal current_time;
3237   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3238
3239   g_source_get_current_time (source, &current_time);
3240   
3241   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3242           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3243            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3244 }
3245
3246 static gboolean
3247 g_timeout_dispatch (GSource     *source,
3248                     GSourceFunc  callback,
3249                     gpointer     user_data)
3250 {
3251   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3252
3253   if (!callback)
3254     {
3255       g_warning ("Timeout source dispatched without callback\n"
3256                  "You must call g_source_set_callback().");
3257       return FALSE;
3258     }
3259  
3260   if (callback (user_data))
3261     {
3262       GTimeVal current_time;
3263
3264       g_source_get_current_time (source, &current_time);
3265       g_timeout_set_expiration (timeout_source, &current_time);
3266
3267       return TRUE;
3268     }
3269   else
3270     return FALSE;
3271 }
3272
3273 /**
3274  * g_timeout_source_new:
3275  * @interval: the timeout interval in milliseconds.
3276  * 
3277  * Creates a new timeout source.
3278  *
3279  * The source will not initially be associated with any #GMainContext
3280  * and must be added to one with g_source_attach() before it will be
3281  * executed.
3282  * 
3283  * Return value: the newly-created timeout source
3284  **/
3285 GSource *
3286 g_timeout_source_new (guint interval)
3287 {
3288   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3289   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3290   GTimeVal current_time;
3291
3292   timeout_source->interval = interval;
3293
3294   g_get_current_time (&current_time);
3295   g_timeout_set_expiration (timeout_source, &current_time);
3296   
3297   return source;
3298 }
3299
3300 /**
3301  * g_timeout_source_new_seconds:
3302  * @interval: the timeout interval in seconds
3303  *
3304  * Creates a new timeout source.
3305  *
3306  * The source will not initially be associated with any #GMainContext
3307  * and must be added to one with g_source_attach() before it will be
3308  * executed.
3309  *
3310  * The scheduling granularity/accuracy of this timeout source will be
3311  * in seconds.
3312  *
3313  * Return value: the newly-created timeout source
3314  *
3315  * Since: 2.14  
3316  **/
3317 GSource *
3318 g_timeout_source_new_seconds (guint interval)
3319 {
3320   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3321   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3322   GTimeVal current_time;
3323
3324   timeout_source->interval = 1000*interval;
3325   timeout_source->granularity = 1000;
3326
3327   g_get_current_time (&current_time);
3328   g_timeout_set_expiration (timeout_source, &current_time);
3329
3330   return source;
3331 }
3332
3333
3334 /**
3335  * g_timeout_add_full:
3336  * @priority: the priority of the timeout source. Typically this will be in
3337  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3338  * @interval: the time between calls to the function, in milliseconds
3339  *             (1/1000ths of a second)
3340  * @function: function to call
3341  * @data:     data to pass to @function
3342  * @notify:   function to call when the timeout is removed, or %NULL
3343  * 
3344  * Sets a function to be called at regular intervals, with the given
3345  * priority.  The function is called repeatedly until it returns
3346  * %FALSE, at which point the timeout is automatically destroyed and
3347  * the function will not be called again.  The @notify function is
3348  * called when the timeout is destroyed.  The first call to the
3349  * function will be at the end of the first @interval.
3350  *
3351  * Note that timeout functions may be delayed, due to the processing of other
3352  * event sources. Thus they should not be relied on for precise timing.
3353  * After each call to the timeout function, the time of the next
3354  * timeout is recalculated based on the current time and the given interval
3355  * (it does not try to 'catch up' time lost in delays).
3356  *
3357  * This internally creates a main loop source using g_timeout_source_new()
3358  * and attaches it to the main loop context using g_source_attach(). You can
3359  * do these steps manually if you need greater control.
3360  * 
3361  * Return value: the ID (greater than 0) of the event source.
3362  **/
3363 guint
3364 g_timeout_add_full (gint           priority,
3365                     guint          interval,
3366                     GSourceFunc    function,
3367                     gpointer       data,
3368                     GDestroyNotify notify)
3369 {
3370   GSource *source;
3371   guint id;
3372   
3373   g_return_val_if_fail (function != NULL, 0);
3374
3375   source = g_timeout_source_new (interval);
3376
3377   if (priority != G_PRIORITY_DEFAULT)
3378     g_source_set_priority (source, priority);
3379
3380   g_source_set_callback (source, function, data, notify);
3381   id = g_source_attach (source, NULL);
3382   g_source_unref (source);
3383
3384   return id;
3385 }
3386
3387 /**
3388  * g_timeout_add:
3389  * @interval: the time between calls to the function, in milliseconds
3390  *             (1/1000ths of a second)
3391  * @function: function to call
3392  * @data:     data to pass to @function
3393  * 
3394  * Sets a function to be called at regular intervals, with the default
3395  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3396  * until it returns %FALSE, at which point the timeout is automatically
3397  * destroyed and the function will not be called again.  The first call
3398  * to the function will be at the end of the first @interval.
3399  *
3400  * Note that timeout functions may be delayed, due to the processing of other
3401  * event sources. Thus they should not be relied on for precise timing.
3402  * After each call to the timeout function, the time of the next
3403  * timeout is recalculated based on the current time and the given interval
3404  * (it does not try to 'catch up' time lost in delays).
3405  *
3406  * If you want to have a timer in the "seconds" range and do not care
3407  * about the exact time of the first call of the timer, use the
3408  * g_timeout_add_seconds() function; this function allows for more
3409  * optimizations and more efficient system power usage.
3410  *
3411  * This internally creates a main loop source using g_timeout_source_new()
3412  * and attaches it to the main loop context using g_source_attach(). You can
3413  * do these steps manually if you need greater control.
3414  * 
3415  * Return value: the ID (greater than 0) of the event source.
3416  **/
3417 guint
3418 g_timeout_add (guint32        interval,
3419                GSourceFunc    function,
3420                gpointer       data)
3421 {
3422   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3423                              interval, function, data, NULL);
3424 }
3425
3426 /**
3427  * g_timeout_add_seconds_full:
3428  * @priority: the priority of the timeout source. Typically this will be in
3429  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3430  * @interval: the time between calls to the function, in seconds
3431  * @function: function to call
3432  * @data:     data to pass to @function
3433  * @notify:   function to call when the timeout is removed, or %NULL
3434  *
3435  * Sets a function to be called at regular intervals, with @priority.
3436  * The function is called repeatedly until it returns %FALSE, at which
3437  * point the timeout is automatically destroyed and the function will
3438  * not be called again.
3439  *
3440  * Unlike g_timeout_add(), this function operates at whole second granularity.
3441  * The initial starting point of the timer is determined by the implementation
3442  * and the implementation is expected to group multiple timers together so that
3443  * they fire all at the same time.
3444  * To allow this grouping, the @interval to the first timer is rounded
3445  * and can deviate up to one second from the specified interval.
3446  * Subsequent timer iterations will generally run at the specified interval.
3447  *
3448  * Note that timeout functions may be delayed, due to the processing of other
3449  * event sources. Thus they should not be relied on for precise timing.
3450  * After each call to the timeout function, the time of the next
3451  * timeout is recalculated based on the current time and the given @interval
3452  *
3453  * If you want timing more precise than whole seconds, use g_timeout_add()
3454  * instead.
3455  *
3456  * The grouping of timers to fire at the same time results in a more power
3457  * and CPU efficient behavior so if your timer is in multiples of seconds
3458  * and you don't require the first timer exactly one second from now, the
3459  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3460  *
3461  * This internally creates a main loop source using 
3462  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3463  * using g_source_attach(). You can do these steps manually if you need 
3464  * greater control.
3465  * 
3466  * Return value: the ID (greater than 0) of the event source.
3467  *
3468  * Since: 2.14
3469  **/
3470 guint
3471 g_timeout_add_seconds_full (gint           priority,
3472                             guint32        interval,
3473                             GSourceFunc    function,
3474                             gpointer       data,
3475                             GDestroyNotify notify)
3476 {
3477   GSource *source;
3478   guint id;
3479
3480   g_return_val_if_fail (function != NULL, 0);
3481
3482   source = g_timeout_source_new_seconds (interval);
3483
3484   if (priority != G_PRIORITY_DEFAULT)
3485     g_source_set_priority (source, priority);
3486
3487   g_source_set_callback (source, function, data, notify);
3488   id = g_source_attach (source, NULL);
3489   g_source_unref (source);
3490
3491   return id;
3492 }
3493
3494 /**
3495  * g_timeout_add_seconds:
3496  * @interval: the time between calls to the function, in seconds
3497  * @function: function to call
3498  * @data: data to pass to @function
3499  *
3500  * Sets a function to be called at regular intervals with the default
3501  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3502  * it returns %FALSE, at which point the timeout is automatically destroyed
3503  * and the function will not be called again.
3504  *
3505  * This internally creates a main loop source using 
3506  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3507  * using g_source_attach(). You can do these steps manually if you need 
3508  * greater control. Also see g_timout_add_seconds_full().
3509  * 
3510  * Return value: the ID (greater than 0) of the event source.
3511  *
3512  * Since: 2.14
3513  **/
3514 guint
3515 g_timeout_add_seconds (guint       interval,
3516                        GSourceFunc function,
3517                        gpointer    data)
3518 {
3519   g_return_val_if_fail (function != NULL, 0);
3520
3521   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3522 }
3523
3524 /* Child watch functions */
3525
3526 #ifdef G_OS_WIN32
3527
3528 static gboolean
3529 g_child_watch_prepare (GSource *source,
3530                        gint    *timeout)
3531 {
3532   *timeout = -1;
3533   return FALSE;
3534 }
3535
3536
3537 static gboolean 
3538 g_child_watch_check (GSource  *source)
3539 {
3540   GChildWatchSource *child_watch_source;
3541   gboolean child_exited;
3542
3543   child_watch_source = (GChildWatchSource *) source;
3544
3545   child_exited = child_watch_source->poll.revents & G_IO_IN;
3546
3547   if (child_exited)
3548     {
3549       DWORD child_status;
3550
3551       /*
3552        * Note: We do _not_ check for the special value of STILL_ACTIVE
3553        * since we know that the process has exited and doing so runs into
3554        * problems if the child process "happens to return STILL_ACTIVE(259)"
3555        * as Microsoft's Platform SDK puts it.
3556        */
3557       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3558         {
3559           gchar *emsg = g_win32_error_message (GetLastError ());
3560           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3561           g_free (emsg);
3562
3563           child_watch_source->child_status = -1;
3564         }
3565       else
3566         child_watch_source->child_status = child_status;
3567     }
3568
3569   return child_exited;
3570 }
3571
3572 #else /* G_OS_WIN32 */
3573
3574 static gboolean
3575 check_for_child_exited (GSource *source)
3576 {
3577   GChildWatchSource *child_watch_source;
3578   gint count;
3579
3580   /* protect against another SIGCHLD in the middle of this call */
3581   count = child_watch_count;
3582
3583   child_watch_source = (GChildWatchSource *) source;
3584
3585   if (child_watch_source->child_exited)
3586     return TRUE;
3587
3588   if (child_watch_source->count < count)
3589     {
3590       gint child_status;
3591
3592       if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3593         {
3594           child_watch_source->child_status = child_status;
3595           child_watch_source->child_exited = TRUE;
3596         }
3597       child_watch_source->count = count;
3598     }
3599
3600   return child_watch_source->child_exited;
3601 }
3602
3603 static gboolean
3604 g_child_watch_prepare (GSource *source,
3605                        gint    *timeout)
3606 {
3607   *timeout = -1;
3608
3609   return check_for_child_exited (source);
3610 }
3611
3612
3613 static gboolean 
3614 g_child_watch_check (GSource  *source)
3615 {
3616   return check_for_child_exited (source);
3617 }
3618
3619 #endif /* G_OS_WIN32 */
3620
3621 static gboolean
3622 g_child_watch_dispatch (GSource    *source, 
3623                         GSourceFunc callback,
3624                         gpointer    user_data)
3625 {
3626   GChildWatchSource *child_watch_source;
3627   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3628
3629   child_watch_source = (GChildWatchSource *) source;
3630
3631   if (!callback)
3632     {
3633       g_warning ("Child watch source dispatched without callback\n"
3634                  "You must call g_source_set_callback().");
3635       return FALSE;
3636     }
3637
3638   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3639
3640   /* We never keep a child watch source around as the child is gone */
3641   return FALSE;
3642 }
3643
3644 #ifndef G_OS_WIN32
3645
3646 static void
3647 g_child_watch_signal_handler (int signum)
3648 {
3649   child_watch_count ++;
3650
3651   if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3652     {
3653       write (child_watch_wake_up_pipe[1], "B", 1);
3654     }
3655   else
3656     {
3657       /* We count on the signal interrupting the poll in the same thread.
3658        */
3659     }
3660 }
3661  
3662 static void
3663 g_child_watch_source_init_single (void)
3664 {
3665   struct sigaction action;
3666
3667   g_assert (! g_thread_supported());
3668   g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3669
3670   child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3671
3672   action.sa_handler = g_child_watch_signal_handler;
3673   sigemptyset (&action.sa_mask);
3674   action.sa_flags = SA_NOCLDSTOP;
3675   sigaction (SIGCHLD, &action, NULL);
3676 }
3677
3678 G_GNUC_NORETURN static gpointer
3679 child_watch_helper_thread (gpointer data) 
3680 {
3681   while (1)
3682     {
3683       gchar b[20];
3684       GSList *list;
3685
3686       read (child_watch_wake_up_pipe[0], b, 20);
3687
3688       /* We were woken up.  Wake up all other contexts in all other threads */
3689       G_LOCK (main_context_list);
3690       for (list = main_context_list; list; list = list->next)
3691         {
3692           GMainContext *context;
3693
3694           context = list->data;
3695           if (g_atomic_int_get (&context->ref_count) > 0)
3696             /* Due to racing conditions we can find ref_count == 0, in
3697              * that case, however, the context is still not destroyed
3698              * and no poll can be active, otherwise the ref_count
3699              * wouldn't be 0 */
3700             g_main_context_wakeup (context);
3701         }
3702       G_UNLOCK (main_context_list);
3703     }
3704 }
3705
3706 static void
3707 g_child_watch_source_init_multi_threaded (void)
3708 {
3709   GError *error = NULL;
3710   struct sigaction action;
3711
3712   g_assert (g_thread_supported());
3713
3714   if (pipe (child_watch_wake_up_pipe) < 0)
3715     g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3716   fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3717
3718   /* We create a helper thread that polls on the wakeup pipe indefinitely */
3719   /* FIXME: Think this through for races */
3720   if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3721     g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3722   child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3723  
3724   action.sa_handler = g_child_watch_signal_handler;
3725   sigemptyset (&action.sa_mask);
3726   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3727   sigaction (SIGCHLD, &action, NULL);
3728 }
3729
3730 static void
3731 g_child_watch_source_init_promote_single_to_threaded (void)
3732 {
3733   g_child_watch_source_init_multi_threaded ();
3734 }
3735
3736 static void
3737 g_child_watch_source_init (void)
3738 {
3739   if (g_thread_supported())
3740     {
3741       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3742         g_child_watch_source_init_multi_threaded ();
3743       else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3744         g_child_watch_source_init_promote_single_to_threaded ();
3745     }
3746   else
3747     {
3748       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3749         g_child_watch_source_init_single ();
3750     }
3751 }
3752
3753 #endif /* !G_OS_WIN32 */
3754
3755 /**
3756  * g_child_watch_source_new:
3757  * @pid: process to watch. On POSIX the pid of a child process. On
3758  * Windows a handle for a process (which doesn't have to be a child).
3759  * 
3760  * Creates a new child_watch source.
3761  *
3762  * The source will not initially be associated with any #GMainContext
3763  * and must be added to one with g_source_attach() before it will be
3764  * executed.
3765  * 
3766  * Note that child watch sources can only be used in conjunction with
3767  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3768  * flag is used.
3769  *
3770  * Note that on platforms where #GPid must be explicitly closed
3771  * (see g_spawn_close_pid()) @pid must not be closed while the
3772  * source is still active. Typically, you will want to call
3773  * g_spawn_close_pid() in the callback function for the source.
3774  *
3775  * Note further that using g_child_watch_source_new() is not 
3776  * compatible with calling <literal>waitpid(-1)</literal> in 
3777  * the application. Calling waitpid() for individual pids will
3778  * still work fine. 
3779  * 
3780  * Return value: the newly-created child watch source
3781  *
3782  * Since: 2.4
3783  **/
3784 GSource *
3785 g_child_watch_source_new (GPid pid)
3786 {
3787   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
3788   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
3789
3790 #ifdef G_OS_WIN32
3791   child_watch_source->poll.fd = (gintptr) pid;
3792   child_watch_source->poll.events = G_IO_IN;
3793
3794   g_source_add_poll (source, &child_watch_source->poll);
3795 #else /* G_OS_WIN32 */
3796   g_child_watch_source_init ();
3797 #endif /* G_OS_WIN32 */
3798
3799   child_watch_source->pid = pid;
3800
3801   return source;
3802 }
3803
3804 /**
3805  * g_child_watch_add_full:
3806  * @priority: the priority of the idle source. Typically this will be in the
3807  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3808  * @pid:      process to watch. On POSIX the pid of a child process. On
3809  * Windows a handle for a process (which doesn't have to be a child).
3810  * @function: function to call
3811  * @data:     data to pass to @function
3812  * @notify:   function to call when the idle is removed, or %NULL
3813  * 
3814  * Sets a function to be called when the child indicated by @pid 
3815  * exits, at the priority @priority.
3816  *
3817  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
3818  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
3819  * the spawn function for the child watching to work.
3820  * 
3821  * Note that on platforms where #GPid must be explicitly closed
3822  * (see g_spawn_close_pid()) @pid must not be closed while the
3823  * source is still active. Typically, you will want to call
3824  * g_spawn_close_pid() in the callback function for the source.
3825  * 
3826  * GLib supports only a single callback per process id.
3827  *
3828  * This internally creates a main loop source using 
3829  * g_child_watch_source_new() and attaches it to the main loop context 
3830  * using g_source_attach(). You can do these steps manually if you 
3831  * need greater control.
3832  *
3833  * Return value: the ID (greater than 0) of the event source.
3834  *
3835  * Since: 2.4
3836  **/
3837 guint
3838 g_child_watch_add_full (gint            priority,
3839                         GPid            pid,
3840                         GChildWatchFunc function,
3841                         gpointer        data,
3842                         GDestroyNotify  notify)
3843 {
3844   GSource *source;
3845   guint id;
3846   
3847   g_return_val_if_fail (function != NULL, 0);
3848
3849   source = g_child_watch_source_new (pid);
3850
3851   if (priority != G_PRIORITY_DEFAULT)
3852     g_source_set_priority (source, priority);
3853
3854   g_source_set_callback (source, (GSourceFunc) function, data, notify);
3855   id = g_source_attach (source, NULL);
3856   g_source_unref (source);
3857
3858   return id;
3859 }
3860
3861 /**
3862  * g_child_watch_add:
3863  * @pid:      process id to watch. On POSIX the pid of a child process. On
3864  * Windows a handle for a process (which doesn't have to be a child).
3865  * @function: function to call
3866  * @data:     data to pass to @function
3867  * 
3868  * Sets a function to be called when the child indicated by @pid 
3869  * exits, at a default priority, #G_PRIORITY_DEFAULT.
3870  * 
3871  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
3872  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
3873  * the spawn function for the child watching to work.
3874  * 
3875  * Note that on platforms where #GPid must be explicitly closed
3876  * (see g_spawn_close_pid()) @pid must not be closed while the
3877  * source is still active. Typically, you will want to call
3878  * g_spawn_close_pid() in the callback function for the source.
3879  *
3880  * GLib supports only a single callback per process id.
3881  *
3882  * This internally creates a main loop source using 
3883  * g_child_watch_source_new() and attaches it to the main loop context 
3884  * using g_source_attach(). You can do these steps manually if you 
3885  * need greater control.
3886  *
3887  * Return value: the ID (greater than 0) of the event source.
3888  *
3889  * Since: 2.4
3890  **/
3891 guint 
3892 g_child_watch_add (GPid            pid,
3893                    GChildWatchFunc function,
3894                    gpointer        data)
3895 {
3896   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
3897 }
3898
3899
3900 /* Idle functions */
3901
3902 static gboolean 
3903 g_idle_prepare  (GSource  *source,
3904                  gint     *timeout)
3905 {
3906   *timeout = 0;
3907
3908   return TRUE;
3909 }
3910
3911 static gboolean 
3912 g_idle_check    (GSource  *source)
3913 {
3914   return TRUE;
3915 }
3916
3917 static gboolean
3918 g_idle_dispatch (GSource    *source, 
3919                  GSourceFunc callback,
3920                  gpointer    user_data)
3921 {
3922   if (!callback)
3923     {
3924       g_warning ("Idle source dispatched without callback\n"
3925                  "You must call g_source_set_callback().");
3926       return FALSE;
3927     }
3928   
3929   return callback (user_data);
3930 }
3931
3932 /**
3933  * g_idle_source_new:
3934  * 
3935  * Creates a new idle source.
3936  *
3937  * The source will not initially be associated with any #GMainContext
3938  * and must be added to one with g_source_attach() before it will be
3939  * executed. Note that the default priority for idle sources is
3940  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
3941  * have a default priority of %G_PRIORITY_DEFAULT.
3942  * 
3943  * Return value: the newly-created idle source
3944  **/
3945 GSource *
3946 g_idle_source_new (void)
3947 {
3948   GSource *source;
3949
3950   source = g_source_new (&g_idle_funcs, sizeof (GSource));
3951   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
3952
3953   return source;
3954 }
3955
3956 /**
3957  * g_idle_add_full:
3958  * @priority: the priority of the idle source. Typically this will be in the
3959  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
3960  * @function: function to call
3961  * @data:     data to pass to @function
3962  * @notify:   function to call when the idle is removed, or %NULL
3963  * 
3964  * Adds a function to be called whenever there are no higher priority
3965  * events pending.  If the function returns %FALSE it is automatically
3966  * removed from the list of event sources and will not be called again.
3967  * 
3968  * This internally creates a main loop source using g_idle_source_new()
3969  * and attaches it to the main loop context using g_source_attach(). 
3970  * You can do these steps manually if you need greater control.
3971  * 
3972  * Return value: the ID (greater than 0) of the event source.
3973  **/
3974 guint 
3975 g_idle_add_full (gint           priority,
3976                  GSourceFunc    function,
3977                  gpointer       data,
3978                  GDestroyNotify notify)
3979 {
3980   GSource *source;
3981   guint id;
3982   
3983   g_return_val_if_fail (function != NULL, 0);
3984
3985   source = g_idle_source_new ();
3986
3987   if (priority != G_PRIORITY_DEFAULT_IDLE)
3988     g_source_set_priority (source, priority);
3989
3990   g_source_set_callback (source, function, data, notify);
3991   id = g_source_attach (source, NULL);
3992   g_source_unref (source);
3993
3994   return id;
3995 }
3996
3997 /**
3998  * g_idle_add:
3999  * @function: function to call 
4000  * @data: data to pass to @function.
4001  * 
4002  * Adds a function to be called whenever there are no higher priority
4003  * events pending to the default main loop. The function is given the
4004  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4005  * returns %FALSE it is automatically removed from the list of event
4006  * sources and will not be called again.
4007  * 
4008  * This internally creates a main loop source using g_idle_source_new()
4009  * and attaches it to the main loop context using g_source_attach(). 
4010  * You can do these steps manually if you need greater control.
4011  * 
4012  * Return value: the ID (greater than 0) of the event source.
4013  **/
4014 guint 
4015 g_idle_add (GSourceFunc    function,
4016             gpointer       data)
4017 {
4018   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4019 }
4020
4021 /**
4022  * g_idle_remove_by_data:
4023  * @data: the data for the idle source's callback.
4024  * 
4025  * Removes the idle function with the given data.
4026  * 
4027  * Return value: %TRUE if an idle source was found and removed.
4028  **/
4029 gboolean
4030 g_idle_remove_by_data (gpointer data)
4031 {
4032   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4033 }
4034
4035 #define __G_MAIN_C__
4036 #include "galiasdef.c"