Stop checking for fork() across GMainContext
[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 #include "glibconfig.h"
36
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38  * enable debugging printouts if the environment variable
39  * G_MAIN_POLL_DEBUG is set to some value.
40  */
41 /* #define G_MAIN_POLL_DEBUG */
42
43 #ifdef _WIN32
44 /* Always enable debugging printout on Windows, as it is more often
45  * needed there...
46  */
47 #define G_MAIN_POLL_DEBUG
48 #endif
49
50 #ifdef G_OS_UNIX
51 #include "glib-unix.h"
52 #include <pthread.h>
53 #ifdef HAVE_EVENTFD
54 #include <sys/eventfd.h>
55 #endif
56 #endif
57
58 #include <signal.h>
59 #include <sys/types.h>
60 #include <time.h>
61 #include <stdlib.h>
62 #ifdef HAVE_SYS_TIME_H
63 #include <sys/time.h>
64 #endif /* HAVE_SYS_TIME_H */
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif /* HAVE_UNISTD_H */
68 #include <errno.h>
69 #include <string.h>
70
71 #ifdef G_OS_WIN32
72 #define STRICT
73 #include <windows.h>
74 #endif /* G_OS_WIN32 */
75
76 #ifdef G_OS_BEOS
77 #include <sys/socket.h>
78 #include <sys/wait.h>
79 #endif /* G_OS_BEOS */
80
81 #include "gmain.h"
82
83 #include "garray.h"
84 #include "giochannel.h"
85 #include "ghash.h"
86 #include "ghook.h"
87 #include "gqueue.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90
91 #ifdef G_OS_WIN32
92 #include "gwin32.h"
93 #endif
94
95 #ifdef  G_MAIN_POLL_DEBUG
96 #include "gtimer.h"
97 #endif
98
99 #include "gwakeup.h"
100
101 #include "glib-private.h"
102
103 /**
104  * SECTION:main
105  * @title: The Main Event Loop
106  * @short_description: manages all available sources of events
107  *
108  * The main event loop manages all the available sources of events for
109  * GLib and GTK+ applications. These events can come from any number of
110  * different types of sources such as file descriptors (plain files,
111  * pipes or sockets) and timeouts. New types of event sources can also
112  * be added using g_source_attach().
113  *
114  * To allow multiple independent sets of sources to be handled in
115  * different threads, each source is associated with a #GMainContext.
116  * A GMainContext can only be running in a single thread, but
117  * sources can be added to it and removed from it from other threads.
118  *
119  * Each event source is assigned a priority. The default priority,
120  * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121  * Values greater than 0 denote lower priorities. Events from high priority
122  * sources are always processed before events from lower priority sources.
123  *
124  * Idle functions can also be added, and assigned a priority. These will
125  * be run whenever no events with a higher priority are ready to be processed.
126  *
127  * The #GMainLoop data type represents a main event loop. A GMainLoop is
128  * created with g_main_loop_new(). After adding the initial event sources,
129  * g_main_loop_run() is called. This continuously checks for new events from
130  * each of the event sources and dispatches them. Finally, the processing of
131  * an event from one of the sources leads to a call to g_main_loop_quit() to
132  * exit the main loop, and g_main_loop_run() returns.
133  *
134  * It is possible to create new instances of #GMainLoop recursively.
135  * This is often used in GTK+ applications when showing modal dialog
136  * boxes. Note that event sources are associated with a particular
137  * #GMainContext, and will be checked and dispatched for all main
138  * loops associated with that GMainContext.
139  *
140  * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141  * gtk_main_quit() and gtk_events_pending().
142  *
143  * <refsect2><title>Creating new source types</title>
144  * <para>One of the unusual features of the #GMainLoop functionality
145  * is that new types of event source can be created and used in
146  * addition to the builtin type of event source. A new event source
147  * type is used for handling GDK events. A new source type is created
148  * by <firstterm>deriving</firstterm> from the #GSource structure.
149  * The derived type of source is represented by a structure that has
150  * the #GSource structure as a first element, and other elements specific
151  * to the new source type. To create an instance of the new source type,
152  * call g_source_new() passing in the size of the derived structure and
153  * a table of functions. These #GSourceFuncs determine the behavior of
154  * the new source type.</para>
155  * <para>New source types basically interact with the main context
156  * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157  * to determine the maximum amount of time that the main loop will sleep
158  * before checking the source again. In addition, or as well, the source
159  * can add file descriptors to the set that the main context checks using
160  * g_source_add_poll().</para>
161  * </refsect2>
162  * <refsect2><title>Customizing the main loop iteration</title>
163  * <para>Single iterations of a #GMainContext can be run with
164  * g_main_context_iteration(). In some cases, more detailed control
165  * of exactly how the details of the main loop work is desired, for
166  * instance, when integrating the #GMainLoop with an external main loop.
167  * In such cases, you can call the component functions of
168  * g_main_context_iteration() directly. These functions are
169  * g_main_context_prepare(), g_main_context_query(),
170  * g_main_context_check() and g_main_context_dispatch().</para>
171  * <para>The operation of these functions can best be seen in terms
172  * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173  * <figure id="mainloop-states"><title>States of a Main Context</title>
174  * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
175  * </figure>
176  * </refsect2>
177  *
178  * On Unix, the GLib mainloop is incompatible with fork().  Any program
179  * using the mainloop must either exec() or exit() from the child
180  * without returning to the mainloop.
181  */
182
183 /* Types */
184
185 typedef struct _GTimeoutSource GTimeoutSource;
186 typedef struct _GChildWatchSource GChildWatchSource;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
188 typedef struct _GPollRec GPollRec;
189 typedef struct _GSourceCallback GSourceCallback;
190
191 typedef enum
192 {
193   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
194   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
195 } GSourceFlags;
196
197 typedef struct _GMainWaiter GMainWaiter;
198
199 struct _GMainWaiter
200 {
201   GCond *cond;
202   GMutex *mutex;
203 };
204
205 typedef struct _GMainDispatch GMainDispatch;
206
207 struct _GMainDispatch
208 {
209   gint depth;
210   GSList *dispatching_sources; /* stack of current sources */
211 };
212
213 #ifdef G_MAIN_POLL_DEBUG
214 gboolean _g_main_poll_debug = FALSE;
215 #endif
216
217 struct _GMainContext
218 {
219   /* The following lock is used for both the list of sources
220    * and the list of poll records
221    */
222   GMutex mutex;
223   GCond cond;
224   GThread *owner;
225   guint owner_count;
226   GSList *waiters;
227
228   gint ref_count;
229
230   GPtrArray *pending_dispatches;
231   gint timeout;                 /* Timeout for current iteration */
232
233   guint next_id;
234   GSource *source_list;
235   gint in_check_or_prepare;
236
237   GPollRec *poll_records, *poll_records_tail;
238   guint n_poll_records;
239   GPollFD *cached_poll_array;
240   guint cached_poll_array_size;
241
242   GWakeup *wakeup;
243
244   GPollFD wake_up_rec;
245
246 /* Flag indicating whether the set of fd's changed during a poll */
247   gboolean poll_changed;
248
249   GPollFunc poll_func;
250
251   gint64   time;
252   gboolean time_is_fresh;
253 };
254
255 struct _GSourceCallback
256 {
257   guint ref_count;
258   GSourceFunc func;
259   gpointer    data;
260   GDestroyNotify notify;
261 };
262
263 struct _GMainLoop
264 {
265   GMainContext *context;
266   gboolean is_running;
267   gint ref_count;
268 };
269
270 struct _GTimeoutSource
271 {
272   GSource     source;
273   gint64      expiration;
274   guint       interval;
275   gboolean    seconds;
276 };
277
278 struct _GChildWatchSource
279 {
280   GSource     source;
281   GPid        pid;
282   gint        child_status;
283 #ifdef G_OS_WIN32
284   GPollFD     poll;
285 #else /* G_OS_WIN32 */
286   gboolean    child_exited;
287 #endif /* G_OS_WIN32 */
288 };
289
290 struct _GUnixSignalWatchSource
291 {
292   GSource     source;
293   int         signum;
294   gboolean    pending;
295 };
296
297 struct _GPollRec
298 {
299   GPollFD *fd;
300   GPollRec *prev;
301   GPollRec *next;
302   gint priority;
303 };
304
305 struct _GSourcePrivate
306 {
307   GSList *child_sources;
308   GSource *parent_source;
309 };
310
311 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
312 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
313 #define G_THREAD_SELF g_thread_self ()
314
315 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
316 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
317                                 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
318
319 #define SOURCE_UNREF(source, context)                       \
320    G_STMT_START {                                           \
321     if ((source)->ref_count > 1)                            \
322       (source)->ref_count--;                                \
323     else                                                    \
324       g_source_unref_internal ((source), (context), TRUE);  \
325    } G_STMT_END
326
327
328 /* Forward declarations */
329
330 static void g_source_unref_internal             (GSource      *source,
331                                                  GMainContext *context,
332                                                  gboolean      have_lock);
333 static void g_source_destroy_internal           (GSource      *source,
334                                                  GMainContext *context,
335                                                  gboolean      have_lock);
336 static void g_source_set_priority_unlocked      (GSource      *source,
337                                                  GMainContext *context,
338                                                  gint          priority);
339 static void g_main_context_poll                 (GMainContext *context,
340                                                  gint          timeout,
341                                                  gint          priority,
342                                                  GPollFD      *fds,
343                                                  gint          n_fds);
344 static void g_main_context_add_poll_unlocked    (GMainContext *context,
345                                                  gint          priority,
346                                                  GPollFD      *fd);
347 static void g_main_context_remove_poll_unlocked (GMainContext *context,
348                                                  GPollFD      *fd);
349
350 static gboolean g_timeout_prepare  (GSource     *source,
351                                     gint        *timeout);
352 static gboolean g_timeout_check    (GSource     *source);
353 static gboolean g_timeout_dispatch (GSource     *source,
354                                     GSourceFunc  callback,
355                                     gpointer     user_data);
356 static gboolean g_child_watch_prepare  (GSource     *source,
357                                         gint        *timeout);
358 static gboolean g_child_watch_check    (GSource     *source);
359 static gboolean g_child_watch_dispatch (GSource     *source,
360                                         GSourceFunc  callback,
361                                         gpointer     user_data);
362 static void     g_child_watch_finalize (GSource     *source);
363 #ifdef G_OS_UNIX
364 static void g_unix_signal_handler (int signum);
365 static gboolean g_unix_signal_watch_prepare  (GSource     *source,
366                                               gint        *timeout);
367 static gboolean g_unix_signal_watch_check    (GSource     *source);
368 static gboolean g_unix_signal_watch_dispatch (GSource     *source,
369                                               GSourceFunc  callback,
370                                               gpointer     user_data);
371 static void     g_unix_signal_watch_finalize  (GSource     *source);
372 #endif
373 static gboolean g_idle_prepare     (GSource     *source,
374                                     gint        *timeout);
375 static gboolean g_idle_check       (GSource     *source);
376 static gboolean g_idle_dispatch    (GSource     *source,
377                                     GSourceFunc  callback,
378                                     gpointer     user_data);
379
380 static GMainContext *glib_worker_context;
381
382 G_LOCK_DEFINE_STATIC (main_loop);
383 static GMainContext *default_main_context;
384
385 #ifndef G_OS_WIN32
386
387
388 /* UNIX signals work by marking one of these variables then waking the
389  * worker context to check on them and dispatch accordingly.
390  */
391 static volatile gchar unix_signal_pending[NSIG];
392 static volatile gboolean any_unix_signal_pending;
393
394 /* Guards all the data below */
395 G_LOCK_DEFINE_STATIC (unix_signal_lock);
396 static GSList *unix_signal_watches;
397 static GSList *unix_child_watches;
398
399 static GSourceFuncs g_unix_signal_funcs =
400 {
401   g_unix_signal_watch_prepare,
402   g_unix_signal_watch_check,
403   g_unix_signal_watch_dispatch,
404   g_unix_signal_watch_finalize
405 };
406 #endif /* !G_OS_WIN32 */
407 G_LOCK_DEFINE_STATIC (main_context_list);
408 static GSList *main_context_list = NULL;
409
410 GSourceFuncs g_timeout_funcs =
411 {
412   g_timeout_prepare,
413   g_timeout_check,
414   g_timeout_dispatch,
415   NULL
416 };
417
418 GSourceFuncs g_child_watch_funcs =
419 {
420   g_child_watch_prepare,
421   g_child_watch_check,
422   g_child_watch_dispatch,
423   g_child_watch_finalize
424 };
425
426 GSourceFuncs g_idle_funcs =
427 {
428   g_idle_prepare,
429   g_idle_check,
430   g_idle_dispatch,
431   NULL
432 };
433
434 /**
435  * g_main_context_ref:
436  * @context: a #GMainContext
437  * 
438  * Increases the reference count on a #GMainContext object by one.
439  *
440  * Returns: the @context that was passed in (since 2.6)
441  **/
442 GMainContext *
443 g_main_context_ref (GMainContext *context)
444 {
445   g_return_val_if_fail (context != NULL, NULL);
446   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL); 
447
448   g_atomic_int_inc (&context->ref_count);
449
450   return context;
451 }
452
453 static inline void
454 poll_rec_list_free (GMainContext *context,
455                     GPollRec     *list)
456 {
457   g_slice_free_chain (GPollRec, list, next);
458 }
459
460 /**
461  * g_main_context_unref:
462  * @context: a #GMainContext
463  * 
464  * Decreases the reference count on a #GMainContext object by one. If
465  * the result is zero, free the context and free all associated memory.
466  **/
467 void
468 g_main_context_unref (GMainContext *context)
469 {
470   GSource *source;
471   g_return_if_fail (context != NULL);
472   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0); 
473
474   if (!g_atomic_int_dec_and_test (&context->ref_count))
475     return;
476
477   G_LOCK (main_context_list);
478   main_context_list = g_slist_remove (main_context_list, context);
479   G_UNLOCK (main_context_list);
480
481   source = context->source_list;
482   while (source)
483     {
484       GSource *next = source->next;
485       g_source_destroy_internal (source, context, FALSE);
486       source = next;
487     }
488
489   g_mutex_clear (&context->mutex);
490
491   g_ptr_array_free (context->pending_dispatches, TRUE);
492   g_free (context->cached_poll_array);
493
494   poll_rec_list_free (context, context->poll_records);
495
496   g_wakeup_free (context->wakeup);
497   g_cond_clear (&context->cond);
498
499   g_free (context);
500 }
501
502 /**
503  * g_main_context_new:
504  * 
505  * Creates a new #GMainContext structure.
506  * 
507  * Return value: the new #GMainContext
508  **/
509 GMainContext *
510 g_main_context_new (void)
511 {
512   static gsize initialised;
513   GMainContext *context;
514
515   if (g_once_init_enter (&initialised))
516     {
517 #ifdef G_MAIN_POLL_DEBUG
518       if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
519         _g_main_poll_debug = TRUE;
520 #endif
521
522       g_once_init_leave (&initialised, TRUE);
523     }
524
525   context = g_new0 (GMainContext, 1);
526
527   g_mutex_init (&context->mutex);
528   g_cond_init (&context->cond);
529
530   context->owner = NULL;
531   context->waiters = NULL;
532
533   context->ref_count = 1;
534
535   context->next_id = 1;
536   
537   context->source_list = NULL;
538   
539   context->poll_func = g_poll;
540   
541   context->cached_poll_array = NULL;
542   context->cached_poll_array_size = 0;
543   
544   context->pending_dispatches = g_ptr_array_new ();
545   
546   context->time_is_fresh = FALSE;
547   
548   context->wakeup = g_wakeup_new ();
549   g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
550   g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
551
552   G_LOCK (main_context_list);
553   main_context_list = g_slist_append (main_context_list, context);
554
555 #ifdef G_MAIN_POLL_DEBUG
556   if (_g_main_poll_debug)
557     g_print ("created context=%p\n", context);
558 #endif
559
560   G_UNLOCK (main_context_list);
561
562   return context;
563 }
564
565 /**
566  * g_main_context_default:
567  * 
568  * Returns the global default main context. This is the main context
569  * used for main loop functions when a main loop is not explicitly
570  * specified, and corresponds to the "main" main loop. See also
571  * g_main_context_get_thread_default().
572  * 
573  * Return value: (transfer none): the global default main context.
574  **/
575 GMainContext *
576 g_main_context_default (void)
577 {
578   /* Slow, but safe */
579   
580   G_LOCK (main_loop);
581
582   if (!default_main_context)
583     {
584       default_main_context = g_main_context_new ();
585 #ifdef G_MAIN_POLL_DEBUG
586       if (_g_main_poll_debug)
587         g_print ("default context=%p\n", default_main_context);
588 #endif
589     }
590
591   G_UNLOCK (main_loop);
592
593   return default_main_context;
594 }
595
596 static void
597 free_context_stack (gpointer data)
598 {
599   GQueue *stack = data;
600   GMainContext *context;
601
602   while (!g_queue_is_empty (stack))
603     {
604       context = g_queue_pop_head (stack);
605       g_main_context_release (context);
606       if (context)
607         g_main_context_unref (context);
608     }
609   g_queue_free (stack);
610 }
611
612 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
613
614 /**
615  * g_main_context_push_thread_default:
616  * @context: a #GMainContext, or %NULL for the global default context
617  *
618  * Acquires @context and sets it as the thread-default context for the
619  * current thread. This will cause certain asynchronous operations
620  * (such as most <link linkend="gio">gio</link>-based I/O) which are
621  * started in this thread to run under @context and deliver their
622  * results to its main loop, rather than running under the global
623  * default context in the main thread. Note that calling this function
624  * changes the context returned by
625  * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
626  * one returned by g_main_context_default(), so it does not affect the
627  * context used by functions like g_idle_add().
628  *
629  * Normally you would call this function shortly after creating a new
630  * thread, passing it a #GMainContext which will be run by a
631  * #GMainLoop in that thread, to set a new default context for all
632  * async operations in that thread. (In this case, you don't need to
633  * ever call g_main_context_pop_thread_default().) In some cases
634  * however, you may want to schedule a single operation in a
635  * non-default context, or temporarily use a non-default context in
636  * the main thread. In that case, you can wrap the call to the
637  * asynchronous operation inside a
638  * g_main_context_push_thread_default() /
639  * g_main_context_pop_thread_default() pair, but it is up to you to
640  * ensure that no other asynchronous operations accidentally get
641  * started while the non-default context is active.
642  *
643  * Beware that libraries that predate this function may not correctly
644  * handle being used from a thread with a thread-default context. Eg,
645  * see g_file_supports_thread_contexts().
646  *
647  * Since: 2.22
648  **/
649 void
650 g_main_context_push_thread_default (GMainContext *context)
651 {
652   GQueue *stack;
653   gboolean acquired_context;
654
655   acquired_context = g_main_context_acquire (context);
656   g_return_if_fail (acquired_context);
657
658   if (context == g_main_context_default ())
659     context = NULL;
660   else if (context)
661     g_main_context_ref (context);
662
663   stack = g_private_get (&thread_context_stack);
664   if (!stack)
665     {
666       stack = g_queue_new ();
667       g_private_set (&thread_context_stack, stack);
668     }
669
670   g_queue_push_head (stack, context);
671 }
672
673 /**
674  * g_main_context_pop_thread_default:
675  * @context: a #GMainContext object, or %NULL
676  *
677  * Pops @context off the thread-default context stack (verifying that
678  * it was on the top of the stack).
679  *
680  * Since: 2.22
681  **/
682 void
683 g_main_context_pop_thread_default (GMainContext *context)
684 {
685   GQueue *stack;
686
687   if (context == g_main_context_default ())
688     context = NULL;
689
690   stack = g_private_get (&thread_context_stack);
691
692   g_return_if_fail (stack != NULL);
693   g_return_if_fail (g_queue_peek_head (stack) == context);
694
695   g_queue_pop_head (stack);
696
697   g_main_context_release (context);
698   if (context)
699     g_main_context_unref (context);
700 }
701
702 /**
703  * g_main_context_get_thread_default:
704  *
705  * Gets the thread-default #GMainContext for this thread. Asynchronous
706  * operations that want to be able to be run in contexts other than
707  * the default one should call this method or
708  * g_main_context_ref_thread_default() to get a #GMainContext to add
709  * their #GSource<!-- -->s to. (Note that even in single-threaded
710  * programs applications may sometimes want to temporarily push a
711  * non-default context, so it is not safe to assume that this will
712  * always return %NULL if you are running in the default thread.)
713  *
714  * If you need to hold a reference on the context, use
715  * g_main_context_ref_thread_default() instead.
716  *
717  * Returns: (transfer none): the thread-default #GMainContext, or
718  * %NULL if the thread-default context is the global default context.
719  *
720  * Since: 2.22
721  **/
722 GMainContext *
723 g_main_context_get_thread_default (void)
724 {
725   GQueue *stack;
726
727   stack = g_private_get (&thread_context_stack);
728   if (stack)
729     return g_queue_peek_head (stack);
730   else
731     return NULL;
732 }
733
734 /**
735  * g_main_context_ref_thread_default:
736  *
737  * Gets the thread-default #GMainContext for this thread, as with
738  * g_main_context_get_thread_default(), but also adds a reference to
739  * it with g_main_context_ref(). In addition, unlike
740  * g_main_context_get_thread_default(), if the thread-default context
741  * is the global default context, this will return that #GMainContext
742  * (with a ref added to it) rather than returning %NULL.
743  *
744  * Returns: (transfer full): the thread-default #GMainContext. Unref
745  *     with g_main_context_unref() when you are done with it.
746  *
747  * Since: 2.32
748  */
749 GMainContext *
750 g_main_context_ref_thread_default (void)
751 {
752   GMainContext *context;
753
754   context = g_main_context_get_thread_default ();
755   if (!context)
756     context = g_main_context_default ();
757   return g_main_context_ref (context);
758 }
759
760 /* Hooks for adding to the main loop */
761
762 /**
763  * g_source_new:
764  * @source_funcs: structure containing functions that implement
765  *                the sources behavior.
766  * @struct_size: size of the #GSource structure to create.
767  * 
768  * Creates a new #GSource structure. The size is specified to
769  * allow creating structures derived from #GSource that contain
770  * additional data. The size passed in must be at least
771  * <literal>sizeof (GSource)</literal>.
772  * 
773  * The source will not initially be associated with any #GMainContext
774  * and must be added to one with g_source_attach() before it will be
775  * executed.
776  * 
777  * Return value: the newly-created #GSource.
778  **/
779 GSource *
780 g_source_new (GSourceFuncs *source_funcs,
781               guint         struct_size)
782 {
783   GSource *source;
784
785   g_return_val_if_fail (source_funcs != NULL, NULL);
786   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
787   
788   source = (GSource*) g_malloc0 (struct_size);
789
790   source->source_funcs = source_funcs;
791   source->ref_count = 1;
792   
793   source->priority = G_PRIORITY_DEFAULT;
794
795   source->flags = G_HOOK_FLAG_ACTIVE;
796
797   /* NULL/0 initialization for all other fields */
798   
799   return source;
800 }
801
802 /* Holds context's lock
803  */
804 static void
805 g_source_list_add (GSource      *source,
806                    GMainContext *context)
807 {
808   GSource *tmp_source, *last_source;
809   
810   if (source->priv && source->priv->parent_source)
811     {
812       /* Put the source immediately before its parent */
813       tmp_source = source->priv->parent_source;
814       last_source = source->priv->parent_source->prev;
815     }
816   else
817     {
818       last_source = NULL;
819       tmp_source = context->source_list;
820       while (tmp_source && tmp_source->priority <= source->priority)
821         {
822           last_source = tmp_source;
823           tmp_source = tmp_source->next;
824         }
825     }
826
827   source->next = tmp_source;
828   if (tmp_source)
829     tmp_source->prev = source;
830   
831   source->prev = last_source;
832   if (last_source)
833     last_source->next = source;
834   else
835     context->source_list = source;
836 }
837
838 /* Holds context's lock
839  */
840 static void
841 g_source_list_remove (GSource      *source,
842                       GMainContext *context)
843 {
844   if (source->prev)
845     source->prev->next = source->next;
846   else
847     context->source_list = source->next;
848
849   if (source->next)
850     source->next->prev = source->prev;
851
852   source->prev = NULL;
853   source->next = NULL;
854 }
855
856 static guint
857 g_source_attach_unlocked (GSource      *source,
858                           GMainContext *context)
859 {
860   guint result = 0;
861   GSList *tmp_list;
862
863   source->context = context;
864   result = source->source_id = context->next_id++;
865
866   source->ref_count++;
867   g_source_list_add (source, context);
868
869   tmp_list = source->poll_fds;
870   while (tmp_list)
871     {
872       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
873       tmp_list = tmp_list->next;
874     }
875
876   if (source->priv)
877     {
878       tmp_list = source->priv->child_sources;
879       while (tmp_list)
880         {
881           g_source_attach_unlocked (tmp_list->data, context);
882           tmp_list = tmp_list->next;
883         }
884     }
885
886   return result;
887 }
888
889 /**
890  * g_source_attach:
891  * @source: a #GSource
892  * @context: a #GMainContext (if %NULL, the default context will be used)
893  * 
894  * Adds a #GSource to a @context so that it will be executed within
895  * that context. Remove it by calling g_source_destroy().
896  *
897  * Return value: the ID (greater than 0) for the source within the 
898  *   #GMainContext. 
899  **/
900 guint
901 g_source_attach (GSource      *source,
902                  GMainContext *context)
903 {
904   guint result = 0;
905
906   g_return_val_if_fail (source->context == NULL, 0);
907   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
908   
909   if (!context)
910     context = g_main_context_default ();
911
912   LOCK_CONTEXT (context);
913
914   result = g_source_attach_unlocked (source, context);
915
916   /* If another thread has acquired the context, wake it up since it
917    * might be in poll() right now.
918    */
919   if (context->owner && context->owner != G_THREAD_SELF)
920     g_wakeup_signal (context->wakeup);
921
922   UNLOCK_CONTEXT (context);
923
924   return result;
925 }
926
927 static void
928 g_source_destroy_internal (GSource      *source,
929                            GMainContext *context,
930                            gboolean      have_lock)
931 {
932   if (!have_lock)
933     LOCK_CONTEXT (context);
934   
935   if (!SOURCE_DESTROYED (source))
936     {
937       GSList *tmp_list;
938       gpointer old_cb_data;
939       GSourceCallbackFuncs *old_cb_funcs;
940       
941       source->flags &= ~G_HOOK_FLAG_ACTIVE;
942
943       old_cb_data = source->callback_data;
944       old_cb_funcs = source->callback_funcs;
945
946       source->callback_data = NULL;
947       source->callback_funcs = NULL;
948
949       if (old_cb_funcs)
950         {
951           UNLOCK_CONTEXT (context);
952           old_cb_funcs->unref (old_cb_data);
953           LOCK_CONTEXT (context);
954         }
955
956       if (!SOURCE_BLOCKED (source))
957         {
958           tmp_list = source->poll_fds;
959           while (tmp_list)
960             {
961               g_main_context_remove_poll_unlocked (context, tmp_list->data);
962               tmp_list = tmp_list->next;
963             }
964         }
965
966       if (source->priv && source->priv->child_sources)
967         {
968           /* This is safe because even if a child_source finalizer or
969            * closure notify tried to modify source->priv->child_sources
970            * from outside the lock, it would fail since
971            * SOURCE_DESTROYED(source) is now TRUE.
972            */
973           tmp_list = source->priv->child_sources;
974           while (tmp_list)
975             {
976               g_source_destroy_internal (tmp_list->data, context, TRUE);
977               g_source_unref_internal (tmp_list->data, context, TRUE);
978               tmp_list = tmp_list->next;
979             }
980           g_slist_free (source->priv->child_sources);
981           source->priv->child_sources = NULL;
982         }
983           
984       g_source_unref_internal (source, context, TRUE);
985     }
986
987   if (!have_lock)
988     UNLOCK_CONTEXT (context);
989 }
990
991 /**
992  * g_source_destroy:
993  * @source: a #GSource
994  * 
995  * Removes a source from its #GMainContext, if any, and mark it as
996  * destroyed.  The source cannot be subsequently added to another
997  * context.
998  **/
999 void
1000 g_source_destroy (GSource *source)
1001 {
1002   GMainContext *context;
1003   
1004   g_return_if_fail (source != NULL);
1005   
1006   context = source->context;
1007   
1008   if (context)
1009     g_source_destroy_internal (source, context, FALSE);
1010   else
1011     source->flags &= ~G_HOOK_FLAG_ACTIVE;
1012 }
1013
1014 /**
1015  * g_source_get_id:
1016  * @source: a #GSource
1017  * 
1018  * Returns the numeric ID for a particular source. The ID of a source
1019  * is a positive integer which is unique within a particular main loop 
1020  * context. The reverse
1021  * mapping from ID to source is done by g_main_context_find_source_by_id().
1022  *
1023  * Return value: the ID (greater than 0) for the source
1024  **/
1025 guint
1026 g_source_get_id (GSource *source)
1027 {
1028   guint result;
1029   
1030   g_return_val_if_fail (source != NULL, 0);
1031   g_return_val_if_fail (source->context != NULL, 0);
1032
1033   LOCK_CONTEXT (source->context);
1034   result = source->source_id;
1035   UNLOCK_CONTEXT (source->context);
1036   
1037   return result;
1038 }
1039
1040 /**
1041  * g_source_get_context:
1042  * @source: a #GSource
1043  * 
1044  * Gets the #GMainContext with which the source is associated.
1045  * Calling this function on a destroyed source is an error.
1046  * 
1047  * Return value: (transfer none): the #GMainContext with which the
1048  *               source is associated, or %NULL if the context has not
1049  *               yet been added to a source.
1050  **/
1051 GMainContext *
1052 g_source_get_context (GSource *source)
1053 {
1054   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1055
1056   return source->context;
1057 }
1058
1059 /**
1060  * g_source_add_poll:
1061  * @source:a #GSource 
1062  * @fd: a #GPollFD structure holding information about a file
1063  *      descriptor to watch.
1064  * 
1065  * Adds a file descriptor to the set of file descriptors polled for
1066  * this source. This is usually combined with g_source_new() to add an
1067  * event source. The event source's check function will typically test
1068  * the @revents field in the #GPollFD struct and return %TRUE if events need
1069  * to be processed.
1070  **/
1071 void
1072 g_source_add_poll (GSource *source,
1073                    GPollFD *fd)
1074 {
1075   GMainContext *context;
1076   
1077   g_return_if_fail (source != NULL);
1078   g_return_if_fail (fd != NULL);
1079   g_return_if_fail (!SOURCE_DESTROYED (source));
1080   
1081   context = source->context;
1082
1083   if (context)
1084     LOCK_CONTEXT (context);
1085   
1086   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1087
1088   if (context)
1089     {
1090       if (!SOURCE_BLOCKED (source))
1091         g_main_context_add_poll_unlocked (context, source->priority, fd);
1092       UNLOCK_CONTEXT (context);
1093     }
1094 }
1095
1096 /**
1097  * g_source_remove_poll:
1098  * @source:a #GSource 
1099  * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1100  * 
1101  * Removes a file descriptor from the set of file descriptors polled for
1102  * this source. 
1103  **/
1104 void
1105 g_source_remove_poll (GSource *source,
1106                       GPollFD *fd)
1107 {
1108   GMainContext *context;
1109   
1110   g_return_if_fail (source != NULL);
1111   g_return_if_fail (fd != NULL);
1112   g_return_if_fail (!SOURCE_DESTROYED (source));
1113   
1114   context = source->context;
1115
1116   if (context)
1117     LOCK_CONTEXT (context);
1118   
1119   source->poll_fds = g_slist_remove (source->poll_fds, fd);
1120
1121   if (context)
1122     {
1123       if (!SOURCE_BLOCKED (source))
1124         g_main_context_remove_poll_unlocked (context, fd);
1125       UNLOCK_CONTEXT (context);
1126     }
1127 }
1128
1129 /**
1130  * g_source_add_child_source:
1131  * @source:a #GSource
1132  * @child_source: a second #GSource that @source should "poll"
1133  *
1134  * Adds @child_source to @source as a "polled" source; when @source is
1135  * added to a #GMainContext, @child_source will be automatically added
1136  * with the same priority, when @child_source is triggered, it will
1137  * cause @source to dispatch (in addition to calling its own
1138  * callback), and when @source is destroyed, it will destroy
1139  * @child_source as well. (@source will also still be dispatched if
1140  * its own prepare/check functions indicate that it is ready.)
1141  *
1142  * If you don't need @child_source to do anything on its own when it
1143  * triggers, you can call g_source_set_dummy_callback() on it to set a
1144  * callback that does nothing (except return %TRUE if appropriate).
1145  *
1146  * @source will hold a reference on @child_source while @child_source
1147  * is attached to it.
1148  *
1149  * Since: 2.28
1150  **/
1151 void
1152 g_source_add_child_source (GSource *source,
1153                            GSource *child_source)
1154 {
1155   GMainContext *context;
1156
1157   g_return_if_fail (source != NULL);
1158   g_return_if_fail (child_source != NULL);
1159   g_return_if_fail (!SOURCE_DESTROYED (source));
1160   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1161   g_return_if_fail (child_source->context == NULL);
1162   g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1163
1164   context = source->context;
1165
1166   if (context)
1167     LOCK_CONTEXT (context);
1168
1169   if (!source->priv)
1170     source->priv = g_slice_new0 (GSourcePrivate);
1171   if (!child_source->priv)
1172     child_source->priv = g_slice_new0 (GSourcePrivate);
1173
1174   source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1175                                                  g_source_ref (child_source));
1176   child_source->priv->parent_source = source;
1177   g_source_set_priority_unlocked (child_source, context, source->priority);
1178
1179   if (context)
1180     {
1181       UNLOCK_CONTEXT (context);
1182       g_source_attach (child_source, context);
1183     }
1184 }
1185
1186 /**
1187  * g_source_remove_child_source:
1188  * @source:a #GSource
1189  * @child_source: a #GSource previously passed to
1190  *     g_source_add_child_source().
1191  *
1192  * Detaches @child_source from @source and destroys it.
1193  *
1194  * Since: 2.28
1195  **/
1196 void
1197 g_source_remove_child_source (GSource *source,
1198                               GSource *child_source)
1199 {
1200   GMainContext *context;
1201
1202   g_return_if_fail (source != NULL);
1203   g_return_if_fail (child_source != NULL);
1204   g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1205   g_return_if_fail (!SOURCE_DESTROYED (source));
1206   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1207
1208   context = source->context;
1209
1210   if (context)
1211     LOCK_CONTEXT (context);
1212
1213   source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1214   g_source_destroy_internal (child_source, context, TRUE);
1215   g_source_unref_internal (child_source, context, TRUE);
1216
1217   if (context)
1218     UNLOCK_CONTEXT (context);
1219 }
1220
1221 /**
1222  * g_source_set_callback_indirect:
1223  * @source: the source
1224  * @callback_data: pointer to callback data "object"
1225  * @callback_funcs: functions for reference counting @callback_data
1226  *                  and getting the callback and data
1227  * 
1228  * Sets the callback function storing the data as a refcounted callback
1229  * "object". This is used internally. Note that calling 
1230  * g_source_set_callback_indirect() assumes
1231  * an initial reference count on @callback_data, and thus
1232  * @callback_funcs->unref will eventually be called once more
1233  * than @callback_funcs->ref.
1234  **/
1235 void
1236 g_source_set_callback_indirect (GSource              *source,
1237                                 gpointer              callback_data,
1238                                 GSourceCallbackFuncs *callback_funcs)
1239 {
1240   GMainContext *context;
1241   gpointer old_cb_data;
1242   GSourceCallbackFuncs *old_cb_funcs;
1243   
1244   g_return_if_fail (source != NULL);
1245   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1246
1247   context = source->context;
1248
1249   if (context)
1250     LOCK_CONTEXT (context);
1251
1252   old_cb_data = source->callback_data;
1253   old_cb_funcs = source->callback_funcs;
1254
1255   source->callback_data = callback_data;
1256   source->callback_funcs = callback_funcs;
1257   
1258   if (context)
1259     UNLOCK_CONTEXT (context);
1260   
1261   if (old_cb_funcs)
1262     old_cb_funcs->unref (old_cb_data);
1263 }
1264
1265 static void
1266 g_source_callback_ref (gpointer cb_data)
1267 {
1268   GSourceCallback *callback = cb_data;
1269
1270   callback->ref_count++;
1271 }
1272
1273
1274 static void
1275 g_source_callback_unref (gpointer cb_data)
1276 {
1277   GSourceCallback *callback = cb_data;
1278
1279   callback->ref_count--;
1280   if (callback->ref_count == 0)
1281     {
1282       if (callback->notify)
1283         callback->notify (callback->data);
1284       g_free (callback);
1285     }
1286 }
1287
1288 static void
1289 g_source_callback_get (gpointer     cb_data,
1290                        GSource     *source, 
1291                        GSourceFunc *func,
1292                        gpointer    *data)
1293 {
1294   GSourceCallback *callback = cb_data;
1295
1296   *func = callback->func;
1297   *data = callback->data;
1298 }
1299
1300 static GSourceCallbackFuncs g_source_callback_funcs = {
1301   g_source_callback_ref,
1302   g_source_callback_unref,
1303   g_source_callback_get,
1304 };
1305
1306 /**
1307  * g_source_set_callback:
1308  * @source: the source
1309  * @func: a callback function
1310  * @data: the data to pass to callback function
1311  * @notify: a function to call when @data is no longer in use, or %NULL.
1312  * 
1313  * Sets the callback function for a source. The callback for a source is
1314  * called from the source's dispatch function.
1315  *
1316  * The exact type of @func depends on the type of source; ie. you
1317  * should not count on @func being called with @data as its first
1318  * parameter.
1319  * 
1320  * Typically, you won't use this function. Instead use functions specific
1321  * to the type of source you are using.
1322  **/
1323 void
1324 g_source_set_callback (GSource        *source,
1325                        GSourceFunc     func,
1326                        gpointer        data,
1327                        GDestroyNotify  notify)
1328 {
1329   GSourceCallback *new_callback;
1330
1331   g_return_if_fail (source != NULL);
1332
1333   new_callback = g_new (GSourceCallback, 1);
1334
1335   new_callback->ref_count = 1;
1336   new_callback->func = func;
1337   new_callback->data = data;
1338   new_callback->notify = notify;
1339
1340   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1341 }
1342
1343
1344 /**
1345  * g_source_set_funcs:
1346  * @source: a #GSource
1347  * @funcs: the new #GSourceFuncs
1348  * 
1349  * Sets the source functions (can be used to override 
1350  * default implementations) of an unattached source.
1351  * 
1352  * Since: 2.12
1353  */
1354 void
1355 g_source_set_funcs (GSource     *source,
1356                    GSourceFuncs *funcs)
1357 {
1358   g_return_if_fail (source != NULL);
1359   g_return_if_fail (source->context == NULL);
1360   g_return_if_fail (source->ref_count > 0);
1361   g_return_if_fail (funcs != NULL);
1362
1363   source->source_funcs = funcs;
1364 }
1365
1366 static void
1367 g_source_set_priority_unlocked (GSource      *source,
1368                                 GMainContext *context,
1369                                 gint          priority)
1370 {
1371   GSList *tmp_list;
1372   
1373   source->priority = priority;
1374
1375   if (context)
1376     {
1377       /* Remove the source from the context's source and then
1378        * add it back so it is sorted in the correct place
1379        */
1380       g_source_list_remove (source, source->context);
1381       g_source_list_add (source, source->context);
1382
1383       if (!SOURCE_BLOCKED (source))
1384         {
1385           tmp_list = source->poll_fds;
1386           while (tmp_list)
1387             {
1388               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1389               g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1390               
1391               tmp_list = tmp_list->next;
1392             }
1393         }
1394     }
1395
1396   if (source->priv && source->priv->child_sources)
1397     {
1398       tmp_list = source->priv->child_sources;
1399       while (tmp_list)
1400         {
1401           g_source_set_priority_unlocked (tmp_list->data, context, priority);
1402           tmp_list = tmp_list->next;
1403         }
1404     }
1405 }
1406
1407 /**
1408  * g_source_set_priority:
1409  * @source: a #GSource
1410  * @priority: the new priority.
1411  *
1412  * Sets the priority of a source. While the main loop is being run, a
1413  * source will be dispatched if it is ready to be dispatched and no
1414  * sources at a higher (numerically smaller) priority are ready to be
1415  * dispatched.
1416  **/
1417 void
1418 g_source_set_priority (GSource  *source,
1419                        gint      priority)
1420 {
1421   GMainContext *context;
1422
1423   g_return_if_fail (source != NULL);
1424
1425   context = source->context;
1426
1427   if (context)
1428     LOCK_CONTEXT (context);
1429   g_source_set_priority_unlocked (source, context, priority);
1430   if (context)
1431     UNLOCK_CONTEXT (source->context);
1432 }
1433
1434 /**
1435  * g_source_get_priority:
1436  * @source: a #GSource
1437  * 
1438  * Gets the priority of a source.
1439  * 
1440  * Return value: the priority of the source
1441  **/
1442 gint
1443 g_source_get_priority (GSource *source)
1444 {
1445   g_return_val_if_fail (source != NULL, 0);
1446
1447   return source->priority;
1448 }
1449
1450 /**
1451  * g_source_set_can_recurse:
1452  * @source: a #GSource
1453  * @can_recurse: whether recursion is allowed for this source
1454  * 
1455  * Sets whether a source can be called recursively. If @can_recurse is
1456  * %TRUE, then while the source is being dispatched then this source
1457  * will be processed normally. Otherwise, all processing of this
1458  * source is blocked until the dispatch function returns.
1459  **/
1460 void
1461 g_source_set_can_recurse (GSource  *source,
1462                           gboolean  can_recurse)
1463 {
1464   GMainContext *context;
1465   
1466   g_return_if_fail (source != NULL);
1467
1468   context = source->context;
1469
1470   if (context)
1471     LOCK_CONTEXT (context);
1472   
1473   if (can_recurse)
1474     source->flags |= G_SOURCE_CAN_RECURSE;
1475   else
1476     source->flags &= ~G_SOURCE_CAN_RECURSE;
1477
1478   if (context)
1479     UNLOCK_CONTEXT (context);
1480 }
1481
1482 /**
1483  * g_source_get_can_recurse:
1484  * @source: a #GSource
1485  * 
1486  * Checks whether a source is allowed to be called recursively.
1487  * see g_source_set_can_recurse().
1488  * 
1489  * Return value: whether recursion is allowed.
1490  **/
1491 gboolean
1492 g_source_get_can_recurse (GSource  *source)
1493 {
1494   g_return_val_if_fail (source != NULL, FALSE);
1495   
1496   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1497 }
1498
1499
1500 /**
1501  * g_source_set_name:
1502  * @source: a #GSource
1503  * @name: debug name for the source
1504  *
1505  * Sets a name for the source, used in debugging and profiling.
1506  * The name defaults to #NULL.
1507  *
1508  * The source name should describe in a human-readable way
1509  * what the source does. For example, "X11 event queue"
1510  * or "GTK+ repaint idle handler" or whatever it is.
1511  *
1512  * It is permitted to call this function multiple times, but is not
1513  * recommended due to the potential performance impact.  For example,
1514  * one could change the name in the "check" function of a #GSourceFuncs 
1515  * to include details like the event type in the source name.
1516  *
1517  * Since: 2.26
1518  **/
1519 void
1520 g_source_set_name (GSource    *source,
1521                    const char *name)
1522 {
1523   g_return_if_fail (source != NULL);
1524
1525   /* setting back to NULL is allowed, just because it's
1526    * weird if get_name can return NULL but you can't
1527    * set that.
1528    */
1529
1530   g_free (source->name);
1531   source->name = g_strdup (name);
1532 }
1533
1534 /**
1535  * g_source_get_name:
1536  * @source: a #GSource
1537  *
1538  * Gets a name for the source, used in debugging and profiling.
1539  * The name may be #NULL if it has never been set with
1540  * g_source_set_name().
1541  *
1542  * Return value: the name of the source
1543  * Since: 2.26
1544  **/
1545 const char *
1546 g_source_get_name (GSource *source)
1547 {
1548   g_return_val_if_fail (source != NULL, NULL);
1549
1550   return source->name;
1551 }
1552
1553 /**
1554  * g_source_set_name_by_id:
1555  * @tag: a #GSource ID
1556  * @name: debug name for the source
1557  *
1558  * Sets the name of a source using its ID.
1559  *
1560  * This is a convenience utility to set source names from the return
1561  * value of g_idle_add(), g_timeout_add(), etc.
1562  *
1563  * Since: 2.26
1564  **/
1565 void
1566 g_source_set_name_by_id (guint           tag,
1567                          const char     *name)
1568 {
1569   GSource *source;
1570
1571   g_return_if_fail (tag > 0);
1572
1573   source = g_main_context_find_source_by_id (NULL, tag);
1574   if (source == NULL)
1575     return;
1576
1577   g_source_set_name (source, name);
1578 }
1579
1580
1581 /**
1582  * g_source_ref:
1583  * @source: a #GSource
1584  * 
1585  * Increases the reference count on a source by one.
1586  * 
1587  * Return value: @source
1588  **/
1589 GSource *
1590 g_source_ref (GSource *source)
1591 {
1592   GMainContext *context;
1593   
1594   g_return_val_if_fail (source != NULL, NULL);
1595
1596   context = source->context;
1597
1598   if (context)
1599     LOCK_CONTEXT (context);
1600
1601   source->ref_count++;
1602
1603   if (context)
1604     UNLOCK_CONTEXT (context);
1605
1606   return source;
1607 }
1608
1609 /* g_source_unref() but possible to call within context lock
1610  */
1611 static void
1612 g_source_unref_internal (GSource      *source,
1613                          GMainContext *context,
1614                          gboolean      have_lock)
1615 {
1616   gpointer old_cb_data = NULL;
1617   GSourceCallbackFuncs *old_cb_funcs = NULL;
1618
1619   g_return_if_fail (source != NULL);
1620   
1621   if (!have_lock && context)
1622     LOCK_CONTEXT (context);
1623
1624   source->ref_count--;
1625   if (source->ref_count == 0)
1626     {
1627       old_cb_data = source->callback_data;
1628       old_cb_funcs = source->callback_funcs;
1629
1630       source->callback_data = NULL;
1631       source->callback_funcs = NULL;
1632
1633       if (context)
1634         {
1635           if (!SOURCE_DESTROYED (source))
1636             g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1637           g_source_list_remove (source, context);
1638         }
1639
1640       if (source->source_funcs->finalize)
1641         {
1642           if (context)
1643             UNLOCK_CONTEXT (context);
1644           source->source_funcs->finalize (source);
1645           if (context)
1646             LOCK_CONTEXT (context);
1647         }
1648
1649       g_free (source->name);
1650       source->name = NULL;
1651
1652       g_slist_free (source->poll_fds);
1653       source->poll_fds = NULL;
1654
1655       if (source->priv)
1656         {
1657           g_slice_free (GSourcePrivate, source->priv);
1658           source->priv = NULL;
1659         }
1660
1661       g_free (source);
1662     }
1663   
1664   if (!have_lock && context)
1665     UNLOCK_CONTEXT (context);
1666
1667   if (old_cb_funcs)
1668     {
1669       if (have_lock)
1670         UNLOCK_CONTEXT (context);
1671       
1672       old_cb_funcs->unref (old_cb_data);
1673
1674       if (have_lock)
1675         LOCK_CONTEXT (context);
1676     }
1677 }
1678
1679 /**
1680  * g_source_unref:
1681  * @source: a #GSource
1682  * 
1683  * Decreases the reference count of a source by one. If the
1684  * resulting reference count is zero the source and associated
1685  * memory will be destroyed. 
1686  **/
1687 void
1688 g_source_unref (GSource *source)
1689 {
1690   g_return_if_fail (source != NULL);
1691
1692   g_source_unref_internal (source, source->context, FALSE);
1693 }
1694
1695 /**
1696  * g_main_context_find_source_by_id:
1697  * @context: a #GMainContext (if %NULL, the default context will be used)
1698  * @source_id: the source ID, as returned by g_source_get_id(). 
1699  * 
1700  * Finds a #GSource given a pair of context and ID.
1701  * 
1702  * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1703  **/
1704 GSource *
1705 g_main_context_find_source_by_id (GMainContext *context,
1706                                   guint         source_id)
1707 {
1708   GSource *source;
1709   
1710   g_return_val_if_fail (source_id > 0, NULL);
1711
1712   if (context == NULL)
1713     context = g_main_context_default ();
1714   
1715   LOCK_CONTEXT (context);
1716   
1717   source = context->source_list;
1718   while (source)
1719     {
1720       if (!SOURCE_DESTROYED (source) &&
1721           source->source_id == source_id)
1722         break;
1723       source = source->next;
1724     }
1725
1726   UNLOCK_CONTEXT (context);
1727
1728   return source;
1729 }
1730
1731 /**
1732  * g_main_context_find_source_by_funcs_user_data:
1733  * @context: a #GMainContext (if %NULL, the default context will be used).
1734  * @funcs: the @source_funcs passed to g_source_new().
1735  * @user_data: the user data from the callback.
1736  * 
1737  * Finds a source with the given source functions and user data.  If
1738  * multiple sources exist with the same source function and user data,
1739  * the first one found will be returned.
1740  * 
1741  * Return value: (transfer none): the source, if one was found, otherwise %NULL
1742  **/
1743 GSource *
1744 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1745                                                GSourceFuncs *funcs,
1746                                                gpointer      user_data)
1747 {
1748   GSource *source;
1749   
1750   g_return_val_if_fail (funcs != NULL, NULL);
1751
1752   if (context == NULL)
1753     context = g_main_context_default ();
1754   
1755   LOCK_CONTEXT (context);
1756
1757   source = context->source_list;
1758   while (source)
1759     {
1760       if (!SOURCE_DESTROYED (source) &&
1761           source->source_funcs == funcs &&
1762           source->callback_funcs)
1763         {
1764           GSourceFunc callback;
1765           gpointer callback_data;
1766
1767           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1768           
1769           if (callback_data == user_data)
1770             break;
1771         }
1772       source = source->next;
1773     }
1774
1775   UNLOCK_CONTEXT (context);
1776
1777   return source;
1778 }
1779
1780 /**
1781  * g_main_context_find_source_by_user_data:
1782  * @context: a #GMainContext
1783  * @user_data: the user_data for the callback.
1784  * 
1785  * Finds a source with the given user data for the callback.  If
1786  * multiple sources exist with the same user data, the first
1787  * one found will be returned.
1788  * 
1789  * Return value: (transfer none): the source, if one was found, otherwise %NULL
1790  **/
1791 GSource *
1792 g_main_context_find_source_by_user_data (GMainContext *context,
1793                                          gpointer      user_data)
1794 {
1795   GSource *source;
1796   
1797   if (context == NULL)
1798     context = g_main_context_default ();
1799   
1800   LOCK_CONTEXT (context);
1801
1802   source = context->source_list;
1803   while (source)
1804     {
1805       if (!SOURCE_DESTROYED (source) &&
1806           source->callback_funcs)
1807         {
1808           GSourceFunc callback;
1809           gpointer callback_data = NULL;
1810
1811           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1812
1813           if (callback_data == user_data)
1814             break;
1815         }
1816       source = source->next;
1817     }
1818
1819   UNLOCK_CONTEXT (context);
1820
1821   return source;
1822 }
1823
1824 /**
1825  * g_source_remove:
1826  * @tag: the ID of the source to remove.
1827  * 
1828  * Removes the source with the given id from the default main context. 
1829  * The id of
1830  * a #GSource is given by g_source_get_id(), or will be returned by the
1831  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1832  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1833  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1834  *
1835  * See also g_source_destroy(). You must use g_source_destroy() for sources
1836  * added to a non-default main context.
1837  *
1838  * Return value: %TRUE if the source was found and removed.
1839  **/
1840 gboolean
1841 g_source_remove (guint tag)
1842 {
1843   GSource *source;
1844   
1845   g_return_val_if_fail (tag > 0, FALSE);
1846
1847   source = g_main_context_find_source_by_id (NULL, tag);
1848   if (source)
1849     g_source_destroy (source);
1850
1851   return source != NULL;
1852 }
1853
1854 /**
1855  * g_source_remove_by_user_data:
1856  * @user_data: the user_data for the callback.
1857  * 
1858  * Removes a source from the default main loop context given the user
1859  * data for the callback. If multiple sources exist with the same user
1860  * data, only one will be destroyed.
1861  * 
1862  * Return value: %TRUE if a source was found and removed. 
1863  **/
1864 gboolean
1865 g_source_remove_by_user_data (gpointer user_data)
1866 {
1867   GSource *source;
1868   
1869   source = g_main_context_find_source_by_user_data (NULL, user_data);
1870   if (source)
1871     {
1872       g_source_destroy (source);
1873       return TRUE;
1874     }
1875   else
1876     return FALSE;
1877 }
1878
1879 /**
1880  * g_source_remove_by_funcs_user_data:
1881  * @funcs: The @source_funcs passed to g_source_new()
1882  * @user_data: the user data for the callback
1883  * 
1884  * Removes a source from the default main loop context given the
1885  * source functions and user data. If multiple sources exist with the
1886  * same source functions and user data, only one will be destroyed.
1887  * 
1888  * Return value: %TRUE if a source was found and removed. 
1889  **/
1890 gboolean
1891 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1892                                     gpointer      user_data)
1893 {
1894   GSource *source;
1895
1896   g_return_val_if_fail (funcs != NULL, FALSE);
1897
1898   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1899   if (source)
1900     {
1901       g_source_destroy (source);
1902       return TRUE;
1903     }
1904   else
1905     return FALSE;
1906 }
1907
1908 /**
1909  * g_get_current_time:
1910  * @result: #GTimeVal structure in which to store current time.
1911  *
1912  * Equivalent to the UNIX gettimeofday() function, but portable.
1913  *
1914  * You may find g_get_real_time() to be more convenient.
1915  **/
1916 void
1917 g_get_current_time (GTimeVal *result)
1918 {
1919 #ifndef G_OS_WIN32
1920   struct timeval r;
1921
1922   g_return_if_fail (result != NULL);
1923
1924   /*this is required on alpha, there the timeval structs are int's
1925     not longs and a cast only would fail horribly*/
1926   gettimeofday (&r, NULL);
1927   result->tv_sec = r.tv_sec;
1928   result->tv_usec = r.tv_usec;
1929 #else
1930   FILETIME ft;
1931   guint64 time64;
1932
1933   g_return_if_fail (result != NULL);
1934
1935   GetSystemTimeAsFileTime (&ft);
1936   memmove (&time64, &ft, sizeof (FILETIME));
1937
1938   /* Convert from 100s of nanoseconds since 1601-01-01
1939    * to Unix epoch. Yes, this is Y2038 unsafe.
1940    */
1941   time64 -= G_GINT64_CONSTANT (116444736000000000);
1942   time64 /= 10;
1943
1944   result->tv_sec = time64 / 1000000;
1945   result->tv_usec = time64 % 1000000;
1946 #endif
1947 }
1948
1949 /**
1950  * g_get_real_time:
1951  *
1952  * Queries the system wall-clock time.
1953  *
1954  * This call is functionally equivalent to g_get_current_time() except
1955  * that the return value is often more convenient than dealing with a
1956  * #GTimeVal.
1957  *
1958  * You should only use this call if you are actually interested in the real
1959  * wall-clock time.  g_get_monotonic_time() is probably more useful for
1960  * measuring intervals.
1961  *
1962  * Returns: the number of microseconds since January 1, 1970 UTC.
1963  *
1964  * Since: 2.28
1965  **/
1966 gint64
1967 g_get_real_time (void)
1968 {
1969   GTimeVal tv;
1970
1971   g_get_current_time (&tv);
1972
1973   return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1974 }
1975
1976 /**
1977  * g_get_monotonic_time:
1978  *
1979  * Queries the system monotonic time, if available.
1980  *
1981  * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1982  * is a very shallow wrapper for that.  Otherwise, we make a best effort
1983  * that probably involves returning the wall clock time (with at least
1984  * microsecond accuracy, subject to the limitations of the OS kernel).
1985  *
1986  * It's important to note that POSIX %CLOCK_MONOTONIC does not count
1987  * time spent while the machine is suspended.
1988  *
1989  * On Windows, "limitations of the OS kernel" is a rather substantial
1990  * statement.  Depending on the configuration of the system, the wall
1991  * clock time is updated as infrequently as 64 times a second (which
1992  * is approximately every 16ms).
1993  *
1994  * Returns: the monotonic time, in microseconds
1995  *
1996  * Since: 2.28
1997  **/
1998 gint64
1999 g_get_monotonic_time (void)
2000 {
2001 #ifdef HAVE_CLOCK_GETTIME
2002   /* librt clock_gettime() is our first choice */
2003   struct timespec ts;
2004
2005 #ifdef CLOCK_MONOTONIC
2006   clock_gettime (CLOCK_MONOTONIC, &ts);
2007 #else
2008   clock_gettime (CLOCK_REALTIME, &ts);
2009 #endif
2010
2011   /* In theory monotonic time can have any epoch.
2012    *
2013    * glib presently assumes the following:
2014    *
2015    *   1) The epoch comes some time after the birth of Jesus of Nazareth, but
2016    *      not more than 10000 years later.
2017    *
2018    *   2) The current time also falls sometime within this range.
2019    *
2020    * These two reasonable assumptions leave us with a maximum deviation from
2021    * the epoch of 10000 years, or 315569520000000000 seconds.
2022    *
2023    * If we restrict ourselves to this range then the number of microseconds
2024    * will always fit well inside the constraints of a int64 (by a factor of
2025    * about 29).
2026    *
2027    * If you actually hit the following assertion, probably you should file a
2028    * bug against your operating system for being excessively silly.
2029    **/
2030   g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2031             ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2032
2033   return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2034
2035 #else /* !HAVE_CLOCK_GETTIME */
2036
2037   /* It may look like we are discarding accuracy on Windows (since its
2038    * current time is expressed in 100s of nanoseconds) but according to
2039    * many sources, the time is only updated 64 times per second, so
2040    * microsecond accuracy is more than enough.
2041    */
2042   GTimeVal tv;
2043
2044   g_get_current_time (&tv);
2045
2046   return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2047 #endif
2048 }
2049
2050 static void
2051 g_main_dispatch_free (gpointer dispatch)
2052 {
2053   g_slice_free (GMainDispatch, dispatch);
2054 }
2055
2056 /* Running the main loop */
2057
2058 static GMainDispatch *
2059 get_dispatch (void)
2060 {
2061   static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2062   GMainDispatch *dispatch;
2063
2064   dispatch = g_private_get (&depth_private);
2065
2066   if (!dispatch)
2067     {
2068       dispatch = g_slice_new0 (GMainDispatch);
2069       g_private_set (&depth_private, dispatch);
2070     }
2071
2072   return dispatch;
2073 }
2074
2075 /**
2076  * g_main_depth:
2077  *
2078  * Returns the depth of the stack of calls to
2079  * g_main_context_dispatch() on any #GMainContext in the current thread.
2080  *  That is, when called from the toplevel, it gives 0. When
2081  * called from within a callback from g_main_context_iteration()
2082  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
2083  * a callback to a recursive call to g_main_context_iteration(),
2084  * it returns 2. And so forth.
2085  *
2086  * This function is useful in a situation like the following:
2087  * Imagine an extremely simple "garbage collected" system.
2088  *
2089  * |[
2090  * static GList *free_list;
2091  * 
2092  * gpointer
2093  * allocate_memory (gsize size)
2094  * { 
2095  *   gpointer result = g_malloc (size);
2096  *   free_list = g_list_prepend (free_list, result);
2097  *   return result;
2098  * }
2099  * 
2100  * void
2101  * free_allocated_memory (void)
2102  * {
2103  *   GList *l;
2104  *   for (l = free_list; l; l = l->next);
2105  *     g_free (l->data);
2106  *   g_list_free (free_list);
2107  *   free_list = NULL;
2108  *  }
2109  * 
2110  * [...]
2111  * 
2112  * while (TRUE); 
2113  *  {
2114  *    g_main_context_iteration (NULL, TRUE);
2115  *    free_allocated_memory();
2116  *   }
2117  * ]|
2118  *
2119  * This works from an application, however, if you want to do the same
2120  * thing from a library, it gets more difficult, since you no longer
2121  * control the main loop. You might think you can simply use an idle
2122  * function to make the call to free_allocated_memory(), but that
2123  * doesn't work, since the idle function could be called from a
2124  * recursive callback. This can be fixed by using g_main_depth()
2125  *
2126  * |[
2127  * gpointer
2128  * allocate_memory (gsize size)
2129  * { 
2130  *   FreeListBlock *block = g_new (FreeListBlock, 1);
2131  *   block->mem = g_malloc (size);
2132  *   block->depth = g_main_depth ();   
2133  *   free_list = g_list_prepend (free_list, block);
2134  *   return block->mem;
2135  * }
2136  * 
2137  * void
2138  * free_allocated_memory (void)
2139  * {
2140  *   GList *l;
2141  *   
2142  *   int depth = g_main_depth ();
2143  *   for (l = free_list; l; );
2144  *     {
2145  *       GList *next = l->next;
2146  *       FreeListBlock *block = l->data;
2147  *       if (block->depth > depth)
2148  *         {
2149  *           g_free (block->mem);
2150  *           g_free (block);
2151  *           free_list = g_list_delete_link (free_list, l);
2152  *         }
2153  *               
2154  *       l = next;
2155  *     }
2156  *   }
2157  * ]|
2158  *
2159  * There is a temptation to use g_main_depth() to solve
2160  * problems with reentrancy. For instance, while waiting for data
2161  * to be received from the network in response to a menu item,
2162  * the menu item might be selected again. It might seem that
2163  * one could make the menu item's callback return immediately
2164  * and do nothing if g_main_depth() returns a value greater than 1.
2165  * However, this should be avoided since the user then sees selecting
2166  * the menu item do nothing. Furthermore, you'll find yourself adding
2167  * these checks all over your code, since there are doubtless many,
2168  * many things that the user could do. Instead, you can use the
2169  * following techniques:
2170  *
2171  * <orderedlist>
2172  *  <listitem>
2173  *   <para>
2174  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
2175  *     the user from interacting with elements while the main
2176  *     loop is recursing.
2177  *   </para>
2178  *  </listitem>
2179  *  <listitem>
2180  *   <para>
2181  *     Avoid main loop recursion in situations where you can't handle
2182  *     arbitrary  callbacks. Instead, structure your code so that you
2183  *     simply return to the main loop and then get called again when
2184  *     there is more work to do.
2185  *   </para>
2186  *  </listitem>
2187  * </orderedlist>
2188  * 
2189  * Return value: The main loop recursion level in the current thread
2190  **/
2191 int
2192 g_main_depth (void)
2193 {
2194   GMainDispatch *dispatch = get_dispatch ();
2195   return dispatch->depth;
2196 }
2197
2198 /**
2199  * g_main_current_source:
2200  *
2201  * Returns the currently firing source for this thread.
2202  * 
2203  * Return value: (transfer none): The currently firing source or %NULL.
2204  *
2205  * Since: 2.12
2206  */
2207 GSource *
2208 g_main_current_source (void)
2209 {
2210   GMainDispatch *dispatch = get_dispatch ();
2211   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2212 }
2213
2214 /**
2215  * g_source_is_destroyed:
2216  * @source: a #GSource
2217  *
2218  * Returns whether @source has been destroyed.
2219  *
2220  * This is important when you operate upon your objects 
2221  * from within idle handlers, but may have freed the object 
2222  * before the dispatch of your idle handler.
2223  *
2224  * |[
2225  * static gboolean 
2226  * idle_callback (gpointer data)
2227  * {
2228  *   SomeWidget *self = data;
2229  *    
2230  *   GDK_THREADS_ENTER (<!-- -->);
2231  *   /<!-- -->* do stuff with self *<!-- -->/
2232  *   self->idle_id = 0;
2233  *   GDK_THREADS_LEAVE (<!-- -->);
2234  *    
2235  *   return FALSE;
2236  * }
2237  *  
2238  * static void 
2239  * some_widget_do_stuff_later (SomeWidget *self)
2240  * {
2241  *   self->idle_id = g_idle_add (idle_callback, self);
2242  * }
2243  *  
2244  * static void 
2245  * some_widget_finalize (GObject *object)
2246  * {
2247  *   SomeWidget *self = SOME_WIDGET (object);
2248  *    
2249  *   if (self->idle_id)
2250  *     g_source_remove (self->idle_id);
2251  *    
2252  *   G_OBJECT_CLASS (parent_class)->finalize (object);
2253  * }
2254  * ]|
2255  *
2256  * This will fail in a multi-threaded application if the 
2257  * widget is destroyed before the idle handler fires due 
2258  * to the use after free in the callback. A solution, to 
2259  * this particular problem, is to check to if the source
2260  * has already been destroy within the callback.
2261  *
2262  * |[
2263  * static gboolean 
2264  * idle_callback (gpointer data)
2265  * {
2266  *   SomeWidget *self = data;
2267  *   
2268  *   GDK_THREADS_ENTER ();
2269  *   if (!g_source_is_destroyed (g_main_current_source ()))
2270  *     {
2271  *       /<!-- -->* do stuff with self *<!-- -->/
2272  *     }
2273  *   GDK_THREADS_LEAVE ();
2274  *   
2275  *   return FALSE;
2276  * }
2277  * ]|
2278  *
2279  * Return value: %TRUE if the source has been destroyed
2280  *
2281  * Since: 2.12
2282  */
2283 gboolean
2284 g_source_is_destroyed (GSource *source)
2285 {
2286   return SOURCE_DESTROYED (source);
2287 }
2288
2289 /* Temporarily remove all this source's file descriptors from the
2290  * poll(), so that if data comes available for one of the file descriptors
2291  * we don't continually spin in the poll()
2292  */
2293 /* HOLDS: source->context's lock */
2294 static void
2295 block_source (GSource *source)
2296 {
2297   GSList *tmp_list;
2298
2299   g_return_if_fail (!SOURCE_BLOCKED (source));
2300
2301   tmp_list = source->poll_fds;
2302   while (tmp_list)
2303     {
2304       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2305       tmp_list = tmp_list->next;
2306     }
2307 }
2308
2309 /* HOLDS: source->context's lock */
2310 static void
2311 unblock_source (GSource *source)
2312 {
2313   GSList *tmp_list;
2314   
2315   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2316   g_return_if_fail (!SOURCE_DESTROYED (source));
2317   
2318   tmp_list = source->poll_fds;
2319   while (tmp_list)
2320     {
2321       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2322       tmp_list = tmp_list->next;
2323     }
2324 }
2325
2326 /* HOLDS: context's lock */
2327 static void
2328 g_main_dispatch (GMainContext *context)
2329 {
2330   GMainDispatch *current = get_dispatch ();
2331   guint i;
2332
2333   for (i = 0; i < context->pending_dispatches->len; i++)
2334     {
2335       GSource *source = context->pending_dispatches->pdata[i];
2336
2337       context->pending_dispatches->pdata[i] = NULL;
2338       g_assert (source);
2339
2340       source->flags &= ~G_SOURCE_READY;
2341
2342       if (!SOURCE_DESTROYED (source))
2343         {
2344           gboolean was_in_call;
2345           gpointer user_data = NULL;
2346           GSourceFunc callback = NULL;
2347           GSourceCallbackFuncs *cb_funcs;
2348           gpointer cb_data;
2349           gboolean need_destroy;
2350
2351           gboolean (*dispatch) (GSource *,
2352                                 GSourceFunc,
2353                                 gpointer);
2354           GSList current_source_link;
2355
2356           dispatch = source->source_funcs->dispatch;
2357           cb_funcs = source->callback_funcs;
2358           cb_data = source->callback_data;
2359
2360           if (cb_funcs)
2361             cb_funcs->ref (cb_data);
2362           
2363           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2364             block_source (source);
2365           
2366           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2367           source->flags |= G_HOOK_FLAG_IN_CALL;
2368
2369           if (cb_funcs)
2370             cb_funcs->get (cb_data, source, &callback, &user_data);
2371
2372           UNLOCK_CONTEXT (context);
2373
2374           current->depth++;
2375           /* The on-stack allocation of the GSList is unconventional, but
2376            * we know that the lifetime of the link is bounded to this
2377            * function as the link is kept in a thread specific list and
2378            * not manipulated outside of this function and its descendants.
2379            * Avoiding the overhead of a g_slist_alloc() is useful as many
2380            * applications do little more than dispatch events.
2381            *
2382            * This is a performance hack - do not revert to g_slist_prepend()!
2383            */
2384           current_source_link.data = source;
2385           current_source_link.next = current->dispatching_sources;
2386           current->dispatching_sources = &current_source_link;
2387           need_destroy = ! dispatch (source,
2388                                      callback,
2389                                      user_data);
2390           g_assert (current->dispatching_sources == &current_source_link);
2391           current->dispatching_sources = current_source_link.next;
2392           current->depth--;
2393           
2394           if (cb_funcs)
2395             cb_funcs->unref (cb_data);
2396
2397           LOCK_CONTEXT (context);
2398           
2399           if (!was_in_call)
2400             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2401
2402           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2403               !SOURCE_DESTROYED (source))
2404             unblock_source (source);
2405           
2406           /* Note: this depends on the fact that we can't switch
2407            * sources from one main context to another
2408            */
2409           if (need_destroy && !SOURCE_DESTROYED (source))
2410             {
2411               g_assert (source->context == context);
2412               g_source_destroy_internal (source, context, TRUE);
2413             }
2414         }
2415       
2416       SOURCE_UNREF (source, context);
2417     }
2418
2419   g_ptr_array_set_size (context->pending_dispatches, 0);
2420 }
2421
2422 /* Holds context's lock */
2423 static inline GSource *
2424 next_valid_source (GMainContext *context,
2425                    GSource      *source)
2426 {
2427   GSource *new_source = source ? source->next : context->source_list;
2428
2429   while (new_source)
2430     {
2431       if (!SOURCE_DESTROYED (new_source))
2432         {
2433           new_source->ref_count++;
2434           break;
2435         }
2436       
2437       new_source = new_source->next;
2438     }
2439
2440   if (source)
2441     SOURCE_UNREF (source, context);
2442           
2443   return new_source;
2444 }
2445
2446 /**
2447  * g_main_context_acquire:
2448  * @context: a #GMainContext
2449  * 
2450  * Tries to become the owner of the specified context.
2451  * If some other thread is the owner of the context,
2452  * returns %FALSE immediately. Ownership is properly
2453  * recursive: the owner can require ownership again
2454  * and will release ownership when g_main_context_release()
2455  * is called as many times as g_main_context_acquire().
2456  *
2457  * You must be the owner of a context before you
2458  * can call g_main_context_prepare(), g_main_context_query(),
2459  * g_main_context_check(), g_main_context_dispatch().
2460  * 
2461  * Return value: %TRUE if the operation succeeded, and
2462  *   this thread is now the owner of @context.
2463  **/
2464 gboolean 
2465 g_main_context_acquire (GMainContext *context)
2466 {
2467   gboolean result = FALSE;
2468   GThread *self = G_THREAD_SELF;
2469
2470   if (context == NULL)
2471     context = g_main_context_default ();
2472   
2473   LOCK_CONTEXT (context);
2474
2475   if (!context->owner)
2476     {
2477       context->owner = self;
2478       g_assert (context->owner_count == 0);
2479     }
2480
2481   if (context->owner == self)
2482     {
2483       context->owner_count++;
2484       result = TRUE;
2485     }
2486
2487   UNLOCK_CONTEXT (context); 
2488   
2489   return result;
2490 }
2491
2492 /**
2493  * g_main_context_release:
2494  * @context: a #GMainContext
2495  * 
2496  * Releases ownership of a context previously acquired by this thread
2497  * with g_main_context_acquire(). If the context was acquired multiple
2498  * times, the ownership will be released only when g_main_context_release()
2499  * is called as many times as it was acquired.
2500  **/
2501 void
2502 g_main_context_release (GMainContext *context)
2503 {
2504   if (context == NULL)
2505     context = g_main_context_default ();
2506   
2507   LOCK_CONTEXT (context);
2508
2509   context->owner_count--;
2510   if (context->owner_count == 0)
2511     {
2512       context->owner = NULL;
2513
2514       if (context->waiters)
2515         {
2516           GMainWaiter *waiter = context->waiters->data;
2517           gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2518           context->waiters = g_slist_delete_link (context->waiters,
2519                                                   context->waiters);
2520           if (!loop_internal_waiter)
2521             g_mutex_lock (waiter->mutex);
2522           
2523           g_cond_signal (waiter->cond);
2524           
2525           if (!loop_internal_waiter)
2526             g_mutex_unlock (waiter->mutex);
2527         }
2528     }
2529
2530   UNLOCK_CONTEXT (context); 
2531 }
2532
2533 /**
2534  * g_main_context_wait:
2535  * @context: a #GMainContext
2536  * @cond: a condition variable
2537  * @mutex: a mutex, currently held
2538  * 
2539  * Tries to become the owner of the specified context,
2540  * as with g_main_context_acquire(). But if another thread
2541  * is the owner, atomically drop @mutex and wait on @cond until 
2542  * that owner releases ownership or until @cond is signaled, then
2543  * try again (once) to become the owner.
2544  * 
2545  * Return value: %TRUE if the operation succeeded, and
2546  *   this thread is now the owner of @context.
2547  **/
2548 gboolean
2549 g_main_context_wait (GMainContext *context,
2550                      GCond        *cond,
2551                      GMutex       *mutex)
2552 {
2553   gboolean result = FALSE;
2554   GThread *self = G_THREAD_SELF;
2555   gboolean loop_internal_waiter;
2556   
2557   if (context == NULL)
2558     context = g_main_context_default ();
2559
2560   loop_internal_waiter = (mutex == &context->mutex);
2561   
2562   if (!loop_internal_waiter)
2563     LOCK_CONTEXT (context);
2564
2565   if (context->owner && context->owner != self)
2566     {
2567       GMainWaiter waiter;
2568
2569       waiter.cond = cond;
2570       waiter.mutex = mutex;
2571
2572       context->waiters = g_slist_append (context->waiters, &waiter);
2573       
2574       if (!loop_internal_waiter)
2575         UNLOCK_CONTEXT (context);
2576       g_cond_wait (cond, mutex);
2577       if (!loop_internal_waiter)      
2578         LOCK_CONTEXT (context);
2579
2580       context->waiters = g_slist_remove (context->waiters, &waiter);
2581     }
2582
2583   if (!context->owner)
2584     {
2585       context->owner = self;
2586       g_assert (context->owner_count == 0);
2587     }
2588
2589   if (context->owner == self)
2590     {
2591       context->owner_count++;
2592       result = TRUE;
2593     }
2594
2595   if (!loop_internal_waiter)
2596     UNLOCK_CONTEXT (context); 
2597   
2598   return result;
2599 }
2600
2601 /**
2602  * g_main_context_prepare:
2603  * @context: a #GMainContext
2604  * @priority: location to store priority of highest priority
2605  *            source already ready.
2606  * 
2607  * Prepares to poll sources within a main loop. The resulting information
2608  * for polling is determined by calling g_main_context_query ().
2609  * 
2610  * Return value: %TRUE if some source is ready to be dispatched
2611  *               prior to polling.
2612  **/
2613 gboolean
2614 g_main_context_prepare (GMainContext *context,
2615                         gint         *priority)
2616 {
2617   gint i;
2618   gint n_ready = 0;
2619   gint current_priority = G_MAXINT;
2620   GSource *source;
2621
2622   if (context == NULL)
2623     context = g_main_context_default ();
2624   
2625   LOCK_CONTEXT (context);
2626
2627   context->time_is_fresh = FALSE;
2628
2629   if (context->in_check_or_prepare)
2630     {
2631       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2632                  "prepare() member.");
2633       UNLOCK_CONTEXT (context);
2634       return FALSE;
2635     }
2636
2637 #if 0
2638   /* If recursing, finish up current dispatch, before starting over */
2639   if (context->pending_dispatches)
2640     {
2641       if (dispatch)
2642         g_main_dispatch (context, &current_time);
2643       
2644       UNLOCK_CONTEXT (context);
2645       return TRUE;
2646     }
2647 #endif
2648
2649   /* If recursing, clear list of pending dispatches */
2650
2651   for (i = 0; i < context->pending_dispatches->len; i++)
2652     {
2653       if (context->pending_dispatches->pdata[i])
2654         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2655     }
2656   g_ptr_array_set_size (context->pending_dispatches, 0);
2657   
2658   /* Prepare all sources */
2659
2660   context->timeout = -1;
2661   
2662   source = next_valid_source (context, NULL);
2663   while (source)
2664     {
2665       gint source_timeout = -1;
2666
2667       if ((n_ready > 0) && (source->priority > current_priority))
2668         {
2669           SOURCE_UNREF (source, context);
2670           break;
2671         }
2672       if (SOURCE_BLOCKED (source))
2673         goto next;
2674
2675       if (!(source->flags & G_SOURCE_READY))
2676         {
2677           gboolean result;
2678           gboolean (*prepare)  (GSource  *source, 
2679                                 gint     *timeout);
2680
2681           prepare = source->source_funcs->prepare;
2682           context->in_check_or_prepare++;
2683           UNLOCK_CONTEXT (context);
2684
2685           result = (*prepare) (source, &source_timeout);
2686
2687           LOCK_CONTEXT (context);
2688           context->in_check_or_prepare--;
2689
2690           if (result)
2691             {
2692               GSource *ready_source = source;
2693
2694               while (ready_source)
2695                 {
2696                   ready_source->flags |= G_SOURCE_READY;
2697                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2698                 }
2699             }
2700         }
2701
2702       if (source->flags & G_SOURCE_READY)
2703         {
2704           n_ready++;
2705           current_priority = source->priority;
2706           context->timeout = 0;
2707         }
2708       
2709       if (source_timeout >= 0)
2710         {
2711           if (context->timeout < 0)
2712             context->timeout = source_timeout;
2713           else
2714             context->timeout = MIN (context->timeout, source_timeout);
2715         }
2716
2717     next:
2718       source = next_valid_source (context, source);
2719     }
2720
2721   UNLOCK_CONTEXT (context);
2722   
2723   if (priority)
2724     *priority = current_priority;
2725   
2726   return (n_ready > 0);
2727 }
2728
2729 /**
2730  * g_main_context_query:
2731  * @context: a #GMainContext
2732  * @max_priority: maximum priority source to check
2733  * @timeout_: (out): location to store timeout to be used in polling
2734  * @fds: (out caller-allocates) (array length=n_fds): location to
2735  *       store #GPollFD records that need to be polled.
2736  * @n_fds: length of @fds.
2737  * 
2738  * Determines information necessary to poll this main loop.
2739  * 
2740  * Return value: the number of records actually stored in @fds,
2741  *   or, if more than @n_fds records need to be stored, the number
2742  *   of records that need to be stored.
2743  **/
2744 gint
2745 g_main_context_query (GMainContext *context,
2746                       gint          max_priority,
2747                       gint         *timeout,
2748                       GPollFD      *fds,
2749                       gint          n_fds)
2750 {
2751   gint n_poll;
2752   GPollRec *pollrec;
2753   
2754   LOCK_CONTEXT (context);
2755
2756   pollrec = context->poll_records;
2757   n_poll = 0;
2758   while (pollrec && max_priority >= pollrec->priority)
2759     {
2760       /* We need to include entries with fd->events == 0 in the array because
2761        * otherwise if the application changes fd->events behind our back and 
2762        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2763        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2764        * this API, but it occurs in practice.) */
2765       if (n_poll < n_fds)
2766         {
2767           fds[n_poll].fd = pollrec->fd->fd;
2768           /* In direct contradiction to the Unix98 spec, IRIX runs into
2769            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2770            * flags in the events field of the pollfd while it should
2771            * just ignoring them. So we mask them out here.
2772            */
2773           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2774           fds[n_poll].revents = 0;
2775         }
2776
2777       pollrec = pollrec->next;
2778       n_poll++;
2779     }
2780
2781   context->poll_changed = FALSE;
2782   
2783   if (timeout)
2784     {
2785       *timeout = context->timeout;
2786       if (*timeout != 0)
2787         context->time_is_fresh = FALSE;
2788     }
2789   
2790   UNLOCK_CONTEXT (context);
2791
2792   return n_poll;
2793 }
2794
2795 /**
2796  * g_main_context_check:
2797  * @context: a #GMainContext
2798  * @max_priority: the maximum numerical priority of sources to check
2799  * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2800  *       the last call to g_main_context_query()
2801  * @n_fds: return value of g_main_context_query()
2802  * 
2803  * Passes the results of polling back to the main loop.
2804  * 
2805  * Return value: %TRUE if some sources are ready to be dispatched.
2806  **/
2807 gboolean
2808 g_main_context_check (GMainContext *context,
2809                       gint          max_priority,
2810                       GPollFD      *fds,
2811                       gint          n_fds)
2812 {
2813   GSource *source;
2814   GPollRec *pollrec;
2815   gint n_ready = 0;
2816   gint i;
2817    
2818   LOCK_CONTEXT (context);
2819
2820   if (context->in_check_or_prepare)
2821     {
2822       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2823                  "prepare() member.");
2824       UNLOCK_CONTEXT (context);
2825       return FALSE;
2826     }
2827
2828   if (context->wake_up_rec.events)
2829     g_wakeup_acknowledge (context->wakeup);
2830
2831   /* If the set of poll file descriptors changed, bail out
2832    * and let the main loop rerun
2833    */
2834   if (context->poll_changed)
2835     {
2836       UNLOCK_CONTEXT (context);
2837       return FALSE;
2838     }
2839   
2840   pollrec = context->poll_records;
2841   i = 0;
2842   while (i < n_fds)
2843     {
2844       if (pollrec->fd->events)
2845         pollrec->fd->revents = fds[i].revents;
2846
2847       pollrec = pollrec->next;
2848       i++;
2849     }
2850
2851   source = next_valid_source (context, NULL);
2852   while (source)
2853     {
2854       if ((n_ready > 0) && (source->priority > max_priority))
2855         {
2856           SOURCE_UNREF (source, context);
2857           break;
2858         }
2859       if (SOURCE_BLOCKED (source))
2860         goto next;
2861
2862       if (!(source->flags & G_SOURCE_READY))
2863         {
2864           gboolean result;
2865           gboolean (*check) (GSource  *source);
2866
2867           check = source->source_funcs->check;
2868           
2869           context->in_check_or_prepare++;
2870           UNLOCK_CONTEXT (context);
2871           
2872           result = (*check) (source);
2873           
2874           LOCK_CONTEXT (context);
2875           context->in_check_or_prepare--;
2876           
2877           if (result)
2878             {
2879               GSource *ready_source = source;
2880
2881               while (ready_source)
2882                 {
2883                   ready_source->flags |= G_SOURCE_READY;
2884                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2885                 }
2886             }
2887         }
2888
2889       if (source->flags & G_SOURCE_READY)
2890         {
2891           source->ref_count++;
2892           g_ptr_array_add (context->pending_dispatches, source);
2893
2894           n_ready++;
2895
2896           /* never dispatch sources with less priority than the first
2897            * one we choose to dispatch
2898            */
2899           max_priority = source->priority;
2900         }
2901
2902     next:
2903       source = next_valid_source (context, source);
2904     }
2905
2906   UNLOCK_CONTEXT (context);
2907
2908   return n_ready > 0;
2909 }
2910
2911 /**
2912  * g_main_context_dispatch:
2913  * @context: a #GMainContext
2914  * 
2915  * Dispatches all pending sources.
2916  **/
2917 void
2918 g_main_context_dispatch (GMainContext *context)
2919 {
2920   LOCK_CONTEXT (context);
2921
2922   if (context->pending_dispatches->len > 0)
2923     {
2924       g_main_dispatch (context);
2925     }
2926
2927   UNLOCK_CONTEXT (context);
2928 }
2929
2930 /* HOLDS context lock */
2931 static gboolean
2932 g_main_context_iterate (GMainContext *context,
2933                         gboolean      block,
2934                         gboolean      dispatch,
2935                         GThread      *self)
2936 {
2937   gint max_priority;
2938   gint timeout;
2939   gboolean some_ready;
2940   gint nfds, allocated_nfds;
2941   GPollFD *fds = NULL;
2942
2943   UNLOCK_CONTEXT (context);
2944
2945   if (!g_main_context_acquire (context))
2946     {
2947       gboolean got_ownership;
2948
2949       LOCK_CONTEXT (context);
2950
2951       if (!block)
2952         return FALSE;
2953
2954       got_ownership = g_main_context_wait (context,
2955                                            &context->cond,
2956                                            &context->mutex);
2957
2958       if (!got_ownership)
2959         return FALSE;
2960     }
2961   else
2962     LOCK_CONTEXT (context);
2963   
2964   if (!context->cached_poll_array)
2965     {
2966       context->cached_poll_array_size = context->n_poll_records;
2967       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2968     }
2969
2970   allocated_nfds = context->cached_poll_array_size;
2971   fds = context->cached_poll_array;
2972   
2973   UNLOCK_CONTEXT (context);
2974
2975   g_main_context_prepare (context, &max_priority); 
2976   
2977   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2978                                        allocated_nfds)) > allocated_nfds)
2979     {
2980       LOCK_CONTEXT (context);
2981       g_free (fds);
2982       context->cached_poll_array_size = allocated_nfds = nfds;
2983       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2984       UNLOCK_CONTEXT (context);
2985     }
2986
2987   if (!block)
2988     timeout = 0;
2989   
2990   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2991   
2992   some_ready = g_main_context_check (context, max_priority, fds, nfds);
2993   
2994   if (dispatch)
2995     g_main_context_dispatch (context);
2996   
2997   g_main_context_release (context);
2998
2999   LOCK_CONTEXT (context);
3000
3001   return some_ready;
3002 }
3003
3004 /**
3005  * g_main_context_pending:
3006  * @context: a #GMainContext (if %NULL, the default context will be used)
3007  *
3008  * Checks if any sources have pending events for the given context.
3009  * 
3010  * Return value: %TRUE if events are pending.
3011  **/
3012 gboolean 
3013 g_main_context_pending (GMainContext *context)
3014 {
3015   gboolean retval;
3016
3017   if (!context)
3018     context = g_main_context_default();
3019
3020   LOCK_CONTEXT (context);
3021   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3022   UNLOCK_CONTEXT (context);
3023   
3024   return retval;
3025 }
3026
3027 /**
3028  * g_main_context_iteration:
3029  * @context: a #GMainContext (if %NULL, the default context will be used) 
3030  * @may_block: whether the call may block.
3031  * 
3032  * Runs a single iteration for the given main loop. This involves
3033  * checking to see if any event sources are ready to be processed,
3034  * then if no events sources are ready and @may_block is %TRUE, waiting
3035  * for a source to become ready, then dispatching the highest priority
3036  * events sources that are ready. Otherwise, if @may_block is %FALSE 
3037  * sources are not waited to become ready, only those highest priority 
3038  * events sources will be dispatched (if any), that are ready at this 
3039  * given moment without further waiting.
3040  *
3041  * Note that even when @may_block is %TRUE, it is still possible for 
3042  * g_main_context_iteration() to return %FALSE, since the the wait may 
3043  * be interrupted for other reasons than an event source becoming ready.
3044  * 
3045  * Return value: %TRUE if events were dispatched.
3046  **/
3047 gboolean
3048 g_main_context_iteration (GMainContext *context, gboolean may_block)
3049 {
3050   gboolean retval;
3051
3052   if (!context)
3053     context = g_main_context_default();
3054   
3055   LOCK_CONTEXT (context);
3056   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3057   UNLOCK_CONTEXT (context);
3058   
3059   return retval;
3060 }
3061
3062 /**
3063  * g_main_loop_new:
3064  * @context: (allow-none): a #GMainContext  (if %NULL, the default context will be used).
3065  * @is_running: set to %TRUE to indicate that the loop is running. This
3066  * is not very important since calling g_main_loop_run() will set this to
3067  * %TRUE anyway.
3068  * 
3069  * Creates a new #GMainLoop structure.
3070  * 
3071  * Return value: a new #GMainLoop.
3072  **/
3073 GMainLoop *
3074 g_main_loop_new (GMainContext *context,
3075                  gboolean      is_running)
3076 {
3077   GMainLoop *loop;
3078
3079   if (!context)
3080     context = g_main_context_default();
3081   
3082   g_main_context_ref (context);
3083
3084   loop = g_new0 (GMainLoop, 1);
3085   loop->context = context;
3086   loop->is_running = is_running != FALSE;
3087   loop->ref_count = 1;
3088   
3089   return loop;
3090 }
3091
3092 /**
3093  * g_main_loop_ref:
3094  * @loop: a #GMainLoop
3095  * 
3096  * Increases the reference count on a #GMainLoop object by one.
3097  * 
3098  * Return value: @loop
3099  **/
3100 GMainLoop *
3101 g_main_loop_ref (GMainLoop *loop)
3102 {
3103   g_return_val_if_fail (loop != NULL, NULL);
3104   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3105
3106   g_atomic_int_inc (&loop->ref_count);
3107
3108   return loop;
3109 }
3110
3111 /**
3112  * g_main_loop_unref:
3113  * @loop: a #GMainLoop
3114  * 
3115  * Decreases the reference count on a #GMainLoop object by one. If
3116  * the result is zero, free the loop and free all associated memory.
3117  **/
3118 void
3119 g_main_loop_unref (GMainLoop *loop)
3120 {
3121   g_return_if_fail (loop != NULL);
3122   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3123
3124   if (!g_atomic_int_dec_and_test (&loop->ref_count))
3125     return;
3126
3127   g_main_context_unref (loop->context);
3128   g_free (loop);
3129 }
3130
3131 /**
3132  * g_main_loop_run:
3133  * @loop: a #GMainLoop
3134  * 
3135  * Runs a main loop until g_main_loop_quit() is called on the loop.
3136  * If this is called for the thread of the loop's #GMainContext,
3137  * it will process events from the loop, otherwise it will
3138  * simply wait.
3139  **/
3140 void 
3141 g_main_loop_run (GMainLoop *loop)
3142 {
3143   GThread *self = G_THREAD_SELF;
3144
3145   g_return_if_fail (loop != NULL);
3146   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3147
3148   if (!g_main_context_acquire (loop->context))
3149     {
3150       gboolean got_ownership = FALSE;
3151       
3152       /* Another thread owns this context */
3153       LOCK_CONTEXT (loop->context);
3154
3155       g_atomic_int_inc (&loop->ref_count);
3156
3157       if (!loop->is_running)
3158         loop->is_running = TRUE;
3159
3160       while (loop->is_running && !got_ownership)
3161         got_ownership = g_main_context_wait (loop->context,
3162                                              &loop->context->cond,
3163                                              &loop->context->mutex);
3164       
3165       if (!loop->is_running)
3166         {
3167           UNLOCK_CONTEXT (loop->context);
3168           if (got_ownership)
3169             g_main_context_release (loop->context);
3170           g_main_loop_unref (loop);
3171           return;
3172         }
3173
3174       g_assert (got_ownership);
3175     }
3176   else
3177     LOCK_CONTEXT (loop->context);
3178
3179   if (loop->context->in_check_or_prepare)
3180     {
3181       g_warning ("g_main_loop_run(): called recursively from within a source's "
3182                  "check() or prepare() member, iteration not possible.");
3183       return;
3184     }
3185
3186   g_atomic_int_inc (&loop->ref_count);
3187   loop->is_running = TRUE;
3188   while (loop->is_running)
3189     g_main_context_iterate (loop->context, TRUE, TRUE, self);
3190
3191   UNLOCK_CONTEXT (loop->context);
3192   
3193   g_main_context_release (loop->context);
3194   
3195   g_main_loop_unref (loop);
3196 }
3197
3198 /**
3199  * g_main_loop_quit:
3200  * @loop: a #GMainLoop
3201  * 
3202  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3203  * for the loop will return. 
3204  *
3205  * Note that sources that have already been dispatched when 
3206  * g_main_loop_quit() is called will still be executed.
3207  **/
3208 void 
3209 g_main_loop_quit (GMainLoop *loop)
3210 {
3211   g_return_if_fail (loop != NULL);
3212   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3213
3214   LOCK_CONTEXT (loop->context);
3215   loop->is_running = FALSE;
3216   g_wakeup_signal (loop->context->wakeup);
3217
3218   g_cond_broadcast (&loop->context->cond);
3219
3220   UNLOCK_CONTEXT (loop->context);
3221 }
3222
3223 /**
3224  * g_main_loop_is_running:
3225  * @loop: a #GMainLoop.
3226  * 
3227  * Checks to see if the main loop is currently being run via g_main_loop_run().
3228  * 
3229  * Return value: %TRUE if the mainloop is currently being run.
3230  **/
3231 gboolean
3232 g_main_loop_is_running (GMainLoop *loop)
3233 {
3234   g_return_val_if_fail (loop != NULL, FALSE);
3235   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3236
3237   return loop->is_running;
3238 }
3239
3240 /**
3241  * g_main_loop_get_context:
3242  * @loop: a #GMainLoop.
3243  * 
3244  * Returns the #GMainContext of @loop.
3245  * 
3246  * Return value: (transfer none): the #GMainContext of @loop
3247  **/
3248 GMainContext *
3249 g_main_loop_get_context (GMainLoop *loop)
3250 {
3251   g_return_val_if_fail (loop != NULL, NULL);
3252   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3253  
3254   return loop->context;
3255 }
3256
3257 /* HOLDS: context's lock */
3258 static void
3259 g_main_context_poll (GMainContext *context,
3260                      gint          timeout,
3261                      gint          priority,
3262                      GPollFD      *fds,
3263                      gint          n_fds)
3264 {
3265 #ifdef  G_MAIN_POLL_DEBUG
3266   GTimer *poll_timer;
3267   GPollRec *pollrec;
3268   gint i;
3269 #endif
3270
3271   GPollFunc poll_func;
3272
3273   if (n_fds || timeout != 0)
3274     {
3275 #ifdef  G_MAIN_POLL_DEBUG
3276       if (_g_main_poll_debug)
3277         {
3278           g_print ("polling context=%p n=%d timeout=%d\n",
3279                    context, n_fds, timeout);
3280           poll_timer = g_timer_new ();
3281         }
3282 #endif
3283
3284       LOCK_CONTEXT (context);
3285
3286       poll_func = context->poll_func;
3287       
3288       UNLOCK_CONTEXT (context);
3289       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3290         {
3291 #ifndef G_OS_WIN32
3292           g_warning ("poll(2) failed due to: %s.",
3293                      g_strerror (errno));
3294 #else
3295           /* If g_poll () returns -1, it has already called g_warning() */
3296 #endif
3297         }
3298       
3299 #ifdef  G_MAIN_POLL_DEBUG
3300       if (_g_main_poll_debug)
3301         {
3302           LOCK_CONTEXT (context);
3303
3304           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3305                    n_fds,
3306                    timeout,
3307                    g_timer_elapsed (poll_timer, NULL));
3308           g_timer_destroy (poll_timer);
3309           pollrec = context->poll_records;
3310
3311           while (pollrec != NULL)
3312             {
3313               i = 0;
3314               while (i < n_fds)
3315                 {
3316                   if (fds[i].fd == pollrec->fd->fd &&
3317                       pollrec->fd->events &&
3318                       fds[i].revents)
3319                     {
3320                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3321                       if (fds[i].revents & G_IO_IN)
3322                         g_print ("i");
3323                       if (fds[i].revents & G_IO_OUT)
3324                         g_print ("o");
3325                       if (fds[i].revents & G_IO_PRI)
3326                         g_print ("p");
3327                       if (fds[i].revents & G_IO_ERR)
3328                         g_print ("e");
3329                       if (fds[i].revents & G_IO_HUP)
3330                         g_print ("h");
3331                       if (fds[i].revents & G_IO_NVAL)
3332                         g_print ("n");
3333                       g_print ("]");
3334                     }
3335                   i++;
3336                 }
3337               pollrec = pollrec->next;
3338             }
3339           g_print ("\n");
3340
3341           UNLOCK_CONTEXT (context);
3342         }
3343 #endif
3344     } /* if (n_fds || timeout != 0) */
3345 }
3346
3347 /**
3348  * g_main_context_add_poll:
3349  * @context: a #GMainContext (or %NULL for the default context)
3350  * @fd: a #GPollFD structure holding information about a file
3351  *      descriptor to watch.
3352  * @priority: the priority for this file descriptor which should be
3353  *      the same as the priority used for g_source_attach() to ensure that the
3354  *      file descriptor is polled whenever the results may be needed.
3355  * 
3356  * Adds a file descriptor to the set of file descriptors polled for
3357  * this context. This will very seldom be used directly. Instead
3358  * a typical event source will use g_source_add_poll() instead.
3359  **/
3360 void
3361 g_main_context_add_poll (GMainContext *context,
3362                          GPollFD      *fd,
3363                          gint          priority)
3364 {
3365   if (!context)
3366     context = g_main_context_default ();
3367   
3368   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3369   g_return_if_fail (fd);
3370
3371   LOCK_CONTEXT (context);
3372   g_main_context_add_poll_unlocked (context, priority, fd);
3373   UNLOCK_CONTEXT (context);
3374 }
3375
3376 /* HOLDS: main_loop_lock */
3377 static void 
3378 g_main_context_add_poll_unlocked (GMainContext *context,
3379                                   gint          priority,
3380                                   GPollFD      *fd)
3381 {
3382   GPollRec *prevrec, *nextrec;
3383   GPollRec *newrec = g_slice_new (GPollRec);
3384
3385   /* This file descriptor may be checked before we ever poll */
3386   fd->revents = 0;
3387   newrec->fd = fd;
3388   newrec->priority = priority;
3389
3390   prevrec = context->poll_records_tail;
3391   nextrec = NULL;
3392   while (prevrec && priority < prevrec->priority)
3393     {
3394       nextrec = prevrec;
3395       prevrec = prevrec->prev;
3396     }
3397
3398   if (prevrec)
3399     prevrec->next = newrec;
3400   else
3401     context->poll_records = newrec;
3402
3403   newrec->prev = prevrec;
3404   newrec->next = nextrec;
3405
3406   if (nextrec)
3407     nextrec->prev = newrec;
3408   else 
3409     context->poll_records_tail = newrec;
3410
3411   context->n_poll_records++;
3412
3413   context->poll_changed = TRUE;
3414
3415   /* Now wake up the main loop if it is waiting in the poll() */
3416   g_wakeup_signal (context->wakeup);
3417 }
3418
3419 /**
3420  * g_main_context_remove_poll:
3421  * @context:a #GMainContext 
3422  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3423  * 
3424  * Removes file descriptor from the set of file descriptors to be
3425  * polled for a particular context.
3426  **/
3427 void
3428 g_main_context_remove_poll (GMainContext *context,
3429                             GPollFD      *fd)
3430 {
3431   if (!context)
3432     context = g_main_context_default ();
3433   
3434   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3435   g_return_if_fail (fd);
3436
3437   LOCK_CONTEXT (context);
3438   g_main_context_remove_poll_unlocked (context, fd);
3439   UNLOCK_CONTEXT (context);
3440 }
3441
3442 static void
3443 g_main_context_remove_poll_unlocked (GMainContext *context,
3444                                      GPollFD      *fd)
3445 {
3446   GPollRec *pollrec, *prevrec, *nextrec;
3447
3448   prevrec = NULL;
3449   pollrec = context->poll_records;
3450
3451   while (pollrec)
3452     {
3453       nextrec = pollrec->next;
3454       if (pollrec->fd == fd)
3455         {
3456           if (prevrec != NULL)
3457             prevrec->next = nextrec;
3458           else
3459             context->poll_records = nextrec;
3460
3461           if (nextrec != NULL)
3462             nextrec->prev = prevrec;
3463           else
3464             context->poll_records_tail = prevrec;
3465
3466           g_slice_free (GPollRec, pollrec);
3467
3468           context->n_poll_records--;
3469           break;
3470         }
3471       prevrec = pollrec;
3472       pollrec = nextrec;
3473     }
3474
3475   context->poll_changed = TRUE;
3476   
3477   /* Now wake up the main loop if it is waiting in the poll() */
3478   g_wakeup_signal (context->wakeup);
3479 }
3480
3481 /**
3482  * g_source_get_current_time:
3483  * @source:  a #GSource
3484  * @timeval: #GTimeVal structure in which to store current time.
3485  *
3486  * This function ignores @source and is otherwise the same as
3487  * g_get_current_time().
3488  *
3489  * Deprecated: 2.28: use g_source_get_time() instead
3490  **/
3491 void
3492 g_source_get_current_time (GSource  *source,
3493                            GTimeVal *timeval)
3494 {
3495   g_get_current_time (timeval);
3496 }
3497
3498 /**
3499  * g_source_get_time:
3500  * @source: a #GSource
3501  *
3502  * Gets the time to be used when checking this source. The advantage of
3503  * calling this function over calling g_get_monotonic_time() directly is
3504  * that when checking multiple sources, GLib can cache a single value
3505  * instead of having to repeatedly get the system monotonic time.
3506  *
3507  * The time here is the system monotonic time, if available, or some
3508  * other reasonable alternative otherwise.  See g_get_monotonic_time().
3509  *
3510  * Returns: the monotonic time in microseconds
3511  *
3512  * Since: 2.28
3513  **/
3514 gint64
3515 g_source_get_time (GSource *source)
3516 {
3517   GMainContext *context;
3518   gint64 result;
3519
3520   g_return_val_if_fail (source->context != NULL, 0);
3521
3522   context = source->context;
3523
3524   LOCK_CONTEXT (context);
3525
3526   if (!context->time_is_fresh)
3527     {
3528       context->time = g_get_monotonic_time ();
3529       context->time_is_fresh = TRUE;
3530     }
3531
3532   result = context->time;
3533
3534   UNLOCK_CONTEXT (context);
3535
3536   return result;
3537 }
3538
3539 /**
3540  * g_main_context_set_poll_func:
3541  * @context: a #GMainContext
3542  * @func: the function to call to poll all file descriptors
3543  * 
3544  * Sets the function to use to handle polling of file descriptors. It
3545  * will be used instead of the poll() system call 
3546  * (or GLib's replacement function, which is used where 
3547  * poll() isn't available).
3548  *
3549  * This function could possibly be used to integrate the GLib event
3550  * loop with an external event loop.
3551  **/
3552 void
3553 g_main_context_set_poll_func (GMainContext *context,
3554                               GPollFunc     func)
3555 {
3556   if (!context)
3557     context = g_main_context_default ();
3558   
3559   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3560
3561   LOCK_CONTEXT (context);
3562   
3563   if (func)
3564     context->poll_func = func;
3565   else
3566     context->poll_func = g_poll;
3567
3568   UNLOCK_CONTEXT (context);
3569 }
3570
3571 /**
3572  * g_main_context_get_poll_func:
3573  * @context: a #GMainContext
3574  * 
3575  * Gets the poll function set by g_main_context_set_poll_func().
3576  * 
3577  * Return value: the poll function
3578  **/
3579 GPollFunc
3580 g_main_context_get_poll_func (GMainContext *context)
3581 {
3582   GPollFunc result;
3583   
3584   if (!context)
3585     context = g_main_context_default ();
3586   
3587   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3588
3589   LOCK_CONTEXT (context);
3590   result = context->poll_func;
3591   UNLOCK_CONTEXT (context);
3592
3593   return result;
3594 }
3595
3596 /**
3597  * g_main_context_wakeup:
3598  * @context: a #GMainContext
3599  * 
3600  * If @context is currently waiting in a poll(), interrupt
3601  * the poll(), and continue the iteration process.
3602  **/
3603 void
3604 g_main_context_wakeup (GMainContext *context)
3605 {
3606   if (!context)
3607     context = g_main_context_default ();
3608
3609   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3610
3611   g_wakeup_signal (context->wakeup);
3612 }
3613
3614 /**
3615  * g_main_context_is_owner:
3616  * @context: a #GMainContext
3617  * 
3618  * Determines whether this thread holds the (recursive)
3619  * ownership of this #GMainContext. This is useful to
3620  * know before waiting on another thread that may be
3621  * blocking to get ownership of @context.
3622  *
3623  * Returns: %TRUE if current thread is owner of @context.
3624  *
3625  * Since: 2.10
3626  **/
3627 gboolean
3628 g_main_context_is_owner (GMainContext *context)
3629 {
3630   gboolean is_owner;
3631
3632   if (!context)
3633     context = g_main_context_default ();
3634
3635   LOCK_CONTEXT (context);
3636   is_owner = context->owner == G_THREAD_SELF;
3637   UNLOCK_CONTEXT (context);
3638
3639   return is_owner;
3640 }
3641
3642 /* Timeouts */
3643
3644 static void
3645 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3646                           gint64          current_time)
3647 {
3648   timeout_source->expiration = current_time +
3649                                (guint64) timeout_source->interval * 1000;
3650
3651   if (timeout_source->seconds)
3652     {
3653       gint64 remainder;
3654       static gint timer_perturb = -1;
3655
3656       if (timer_perturb == -1)
3657         {
3658           /*
3659            * we want a per machine/session unique 'random' value; try the dbus
3660            * address first, that has a UUID in it. If there is no dbus, use the
3661            * hostname for hashing.
3662            */
3663           const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3664           if (!session_bus_address)
3665             session_bus_address = g_getenv ("HOSTNAME");
3666           if (session_bus_address)
3667             timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3668           else
3669             timer_perturb = 0;
3670         }
3671
3672       /* We want the microseconds part of the timeout to land on the
3673        * 'timer_perturb' mark, but we need to make sure we don't try to
3674        * set the timeout in the past.  We do this by ensuring that we
3675        * always only *increase* the expiration time by adding a full
3676        * second in the case that the microsecond portion decreases.
3677        */
3678       timeout_source->expiration -= timer_perturb;
3679
3680       remainder = timeout_source->expiration % 1000000;
3681       if (remainder >= 1000000/4)
3682         timeout_source->expiration += 1000000;
3683
3684       timeout_source->expiration -= remainder;
3685       timeout_source->expiration += timer_perturb;
3686     }
3687 }
3688
3689 static gboolean
3690 g_timeout_prepare (GSource *source,
3691                    gint    *timeout)
3692 {
3693   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3694   gint64 now = g_source_get_time (source);
3695
3696   if (now < timeout_source->expiration)
3697     {
3698       /* Round up to ensure that we don't try again too early */
3699       *timeout = (timeout_source->expiration - now + 999) / 1000;
3700       return FALSE;
3701     }
3702
3703   *timeout = 0;
3704   return TRUE;
3705 }
3706
3707 static gboolean 
3708 g_timeout_check (GSource *source)
3709 {
3710   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3711   gint64 now = g_source_get_time (source);
3712
3713   return timeout_source->expiration <= now;
3714 }
3715
3716 static gboolean
3717 g_timeout_dispatch (GSource     *source,
3718                     GSourceFunc  callback,
3719                     gpointer     user_data)
3720 {
3721   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3722   gboolean again;
3723
3724   if (!callback)
3725     {
3726       g_warning ("Timeout source dispatched without callback\n"
3727                  "You must call g_source_set_callback().");
3728       return FALSE;
3729     }
3730
3731   again = callback (user_data);
3732
3733   if (again)
3734     g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3735
3736   return again;
3737 }
3738
3739 /**
3740  * g_timeout_source_new:
3741  * @interval: the timeout interval in milliseconds.
3742  * 
3743  * Creates a new timeout source.
3744  *
3745  * The source will not initially be associated with any #GMainContext
3746  * and must be added to one with g_source_attach() before it will be
3747  * executed.
3748  *
3749  * The interval given is in terms of monotonic time, not wall clock
3750  * time.  See g_get_monotonic_time().
3751  * 
3752  * Return value: the newly-created timeout source
3753  **/
3754 GSource *
3755 g_timeout_source_new (guint interval)
3756 {
3757   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3758   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3759
3760   timeout_source->interval = interval;
3761   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3762
3763   return source;
3764 }
3765
3766 /**
3767  * g_timeout_source_new_seconds:
3768  * @interval: the timeout interval in seconds
3769  *
3770  * Creates a new timeout source.
3771  *
3772  * The source will not initially be associated with any #GMainContext
3773  * and must be added to one with g_source_attach() before it will be
3774  * executed.
3775  *
3776  * The scheduling granularity/accuracy of this timeout source will be
3777  * in seconds.
3778  *
3779  * The interval given in terms of monotonic time, not wall clock time.
3780  * See g_get_monotonic_time().
3781  *
3782  * Return value: the newly-created timeout source
3783  *
3784  * Since: 2.14  
3785  **/
3786 GSource *
3787 g_timeout_source_new_seconds (guint interval)
3788 {
3789   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3790   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3791
3792   timeout_source->interval = 1000 * interval;
3793   timeout_source->seconds = TRUE;
3794
3795   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3796
3797   return source;
3798 }
3799
3800
3801 /**
3802  * g_timeout_add_full:
3803  * @priority: the priority of the timeout source. Typically this will be in
3804  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3805  * @interval: the time between calls to the function, in milliseconds
3806  *             (1/1000ths of a second)
3807  * @function: function to call
3808  * @data:     data to pass to @function
3809  * @notify:   function to call when the timeout is removed, or %NULL
3810  * 
3811  * Sets a function to be called at regular intervals, with the given
3812  * priority.  The function is called repeatedly until it returns
3813  * %FALSE, at which point the timeout is automatically destroyed and
3814  * the function will not be called again.  The @notify function is
3815  * called when the timeout is destroyed.  The first call to the
3816  * function will be at the end of the first @interval.
3817  *
3818  * Note that timeout functions may be delayed, due to the processing of other
3819  * event sources. Thus they should not be relied on for precise timing.
3820  * After each call to the timeout function, the time of the next
3821  * timeout is recalculated based on the current time and the given interval
3822  * (it does not try to 'catch up' time lost in delays).
3823  *
3824  * This internally creates a main loop source using g_timeout_source_new()
3825  * and attaches it to the main loop context using g_source_attach(). You can
3826  * do these steps manually if you need greater control.
3827  *
3828  * The interval given in terms of monotonic time, not wall clock time.
3829  * See g_get_monotonic_time().
3830  * 
3831  * Return value: the ID (greater than 0) of the event source.
3832  * Rename to: g_timeout_add
3833  **/
3834 guint
3835 g_timeout_add_full (gint           priority,
3836                     guint          interval,
3837                     GSourceFunc    function,
3838                     gpointer       data,
3839                     GDestroyNotify notify)
3840 {
3841   GSource *source;
3842   guint id;
3843   
3844   g_return_val_if_fail (function != NULL, 0);
3845
3846   source = g_timeout_source_new (interval);
3847
3848   if (priority != G_PRIORITY_DEFAULT)
3849     g_source_set_priority (source, priority);
3850
3851   g_source_set_callback (source, function, data, notify);
3852   id = g_source_attach (source, NULL);
3853   g_source_unref (source);
3854
3855   return id;
3856 }
3857
3858 /**
3859  * g_timeout_add:
3860  * @interval: the time between calls to the function, in milliseconds
3861  *             (1/1000ths of a second)
3862  * @function: function to call
3863  * @data:     data to pass to @function
3864  * 
3865  * Sets a function to be called at regular intervals, with the default
3866  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3867  * until it returns %FALSE, at which point the timeout is automatically
3868  * destroyed and the function will not be called again.  The first call
3869  * to the function will be at the end of the first @interval.
3870  *
3871  * Note that timeout functions may be delayed, due to the processing of other
3872  * event sources. Thus they should not be relied on for precise timing.
3873  * After each call to the timeout function, the time of the next
3874  * timeout is recalculated based on the current time and the given interval
3875  * (it does not try to 'catch up' time lost in delays).
3876  *
3877  * If you want to have a timer in the "seconds" range and do not care
3878  * about the exact time of the first call of the timer, use the
3879  * g_timeout_add_seconds() function; this function allows for more
3880  * optimizations and more efficient system power usage.
3881  *
3882  * This internally creates a main loop source using g_timeout_source_new()
3883  * and attaches it to the main loop context using g_source_attach(). You can
3884  * do these steps manually if you need greater control.
3885  * 
3886  * The interval given is in terms of monotonic time, not wall clock
3887  * time.  See g_get_monotonic_time().
3888  * 
3889  * Return value: the ID (greater than 0) of the event source.
3890  **/
3891 guint
3892 g_timeout_add (guint32        interval,
3893                GSourceFunc    function,
3894                gpointer       data)
3895 {
3896   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3897                              interval, function, data, NULL);
3898 }
3899
3900 /**
3901  * g_timeout_add_seconds_full:
3902  * @priority: the priority of the timeout source. Typically this will be in
3903  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3904  * @interval: the time between calls to the function, in seconds
3905  * @function: function to call
3906  * @data:     data to pass to @function
3907  * @notify:   function to call when the timeout is removed, or %NULL
3908  *
3909  * Sets a function to be called at regular intervals, with @priority.
3910  * The function is called repeatedly until it returns %FALSE, at which
3911  * point the timeout is automatically destroyed and the function will
3912  * not be called again.
3913  *
3914  * Unlike g_timeout_add(), this function operates at whole second granularity.
3915  * The initial starting point of the timer is determined by the implementation
3916  * and the implementation is expected to group multiple timers together so that
3917  * they fire all at the same time.
3918  * To allow this grouping, the @interval to the first timer is rounded
3919  * and can deviate up to one second from the specified interval.
3920  * Subsequent timer iterations will generally run at the specified interval.
3921  *
3922  * Note that timeout functions may be delayed, due to the processing of other
3923  * event sources. Thus they should not be relied on for precise timing.
3924  * After each call to the timeout function, the time of the next
3925  * timeout is recalculated based on the current time and the given @interval
3926  *
3927  * If you want timing more precise than whole seconds, use g_timeout_add()
3928  * instead.
3929  *
3930  * The grouping of timers to fire at the same time results in a more power
3931  * and CPU efficient behavior so if your timer is in multiples of seconds
3932  * and you don't require the first timer exactly one second from now, the
3933  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3934  *
3935  * This internally creates a main loop source using 
3936  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3937  * using g_source_attach(). You can do these steps manually if you need 
3938  * greater control.
3939  * 
3940  * The interval given is in terms of monotonic time, not wall clock
3941  * time.  See g_get_monotonic_time().
3942  * 
3943  * Return value: the ID (greater than 0) of the event source.
3944  *
3945  * Rename to: g_timeout_add_seconds
3946  * Since: 2.14
3947  **/
3948 guint
3949 g_timeout_add_seconds_full (gint           priority,
3950                             guint32        interval,
3951                             GSourceFunc    function,
3952                             gpointer       data,
3953                             GDestroyNotify notify)
3954 {
3955   GSource *source;
3956   guint id;
3957
3958   g_return_val_if_fail (function != NULL, 0);
3959
3960   source = g_timeout_source_new_seconds (interval);
3961
3962   if (priority != G_PRIORITY_DEFAULT)
3963     g_source_set_priority (source, priority);
3964
3965   g_source_set_callback (source, function, data, notify);
3966   id = g_source_attach (source, NULL);
3967   g_source_unref (source);
3968
3969   return id;
3970 }
3971
3972 /**
3973  * g_timeout_add_seconds:
3974  * @interval: the time between calls to the function, in seconds
3975  * @function: function to call
3976  * @data: data to pass to @function
3977  *
3978  * Sets a function to be called at regular intervals with the default
3979  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3980  * it returns %FALSE, at which point the timeout is automatically destroyed
3981  * and the function will not be called again.
3982  *
3983  * This internally creates a main loop source using
3984  * g_timeout_source_new_seconds() and attaches it to the main loop context
3985  * using g_source_attach(). You can do these steps manually if you need
3986  * greater control. Also see g_timeout_add_seconds_full().
3987  *
3988  * Note that the first call of the timer may not be precise for timeouts
3989  * of one second. If you need finer precision and have such a timeout,
3990  * you may want to use g_timeout_add() instead.
3991  *
3992  * The interval given is in terms of monotonic time, not wall clock
3993  * time.  See g_get_monotonic_time().
3994  * 
3995  * Return value: the ID (greater than 0) of the event source.
3996  *
3997  * Since: 2.14
3998  **/
3999 guint
4000 g_timeout_add_seconds (guint       interval,
4001                        GSourceFunc function,
4002                        gpointer    data)
4003 {
4004   g_return_val_if_fail (function != NULL, 0);
4005
4006   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4007 }
4008
4009 /* Child watch functions */
4010
4011 #ifdef G_OS_WIN32
4012
4013 static gboolean
4014 g_child_watch_prepare (GSource *source,
4015                        gint    *timeout)
4016 {
4017   *timeout = -1;
4018   return FALSE;
4019 }
4020
4021 static gboolean 
4022 g_child_watch_check (GSource  *source)
4023 {
4024   GChildWatchSource *child_watch_source;
4025   gboolean child_exited;
4026
4027   child_watch_source = (GChildWatchSource *) source;
4028
4029   child_exited = child_watch_source->poll.revents & G_IO_IN;
4030
4031   if (child_exited)
4032     {
4033       DWORD child_status;
4034
4035       /*
4036        * Note: We do _not_ check for the special value of STILL_ACTIVE
4037        * since we know that the process has exited and doing so runs into
4038        * problems if the child process "happens to return STILL_ACTIVE(259)"
4039        * as Microsoft's Platform SDK puts it.
4040        */
4041       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4042         {
4043           gchar *emsg = g_win32_error_message (GetLastError ());
4044           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4045           g_free (emsg);
4046
4047           child_watch_source->child_status = -1;
4048         }
4049       else
4050         child_watch_source->child_status = child_status;
4051     }
4052
4053   return child_exited;
4054 }
4055
4056 static void
4057 g_child_watch_finalize (GSource *source)
4058 {
4059 }
4060
4061 #else /* G_OS_WIN32 */
4062
4063 static void
4064 wake_source (GSource *source)
4065 {
4066   GMainContext *context;
4067
4068   /* This should be thread-safe:
4069    *
4070    *  - if the source is currently being added to a context, that
4071    *    context will be woken up anyway
4072    *
4073    *  - if the source is currently being destroyed, we simply need not
4074    *    to crash:
4075    *
4076    *    - the memory for the source will remain valid until after the
4077    *      source finalize function was called (which would remove the
4078    *      source from the global list which we are currently holding the
4079    *      lock for)
4080    *
4081    *    - the GMainContext will either be NULL or point to a live
4082    *      GMainContext
4083    *
4084    *    - the GMainContext will remain valid since we hold the
4085    *      main_context_list lock
4086    *
4087    *  Since we are holding a lot of locks here, don't try to enter any
4088    *  more GMainContext functions for fear of dealock -- just hit the
4089    *  GWakeup and run.  Even if that's safe now, it could easily become
4090    *  unsafe with some very minor changes in the future, and signal
4091    *  handling is not the most well-tested codepath.
4092    */
4093   G_LOCK(main_context_list);
4094   context = source->context;
4095   if (context)
4096     g_wakeup_signal (context->wakeup);
4097   G_UNLOCK(main_context_list);
4098 }
4099
4100 static void
4101 dispatch_unix_signals (void)
4102 {
4103   GSList *node;
4104
4105   /* clear this first incase another one arrives while we're processing */
4106   any_unix_signal_pending = FALSE;
4107
4108   G_LOCK(unix_signal_lock);
4109
4110   /* handle GChildWatchSource instances */
4111   if (unix_signal_pending[SIGCHLD])
4112     {
4113       unix_signal_pending[SIGCHLD] = FALSE;
4114
4115       /* The only way we can do this is to scan all of the children.
4116        *
4117        * The docs promise that we will not reap children that we are not
4118        * explicitly watching, so that ties our hands from calling
4119        * waitpid(-1).  We also can't use siginfo's si_pid field since if
4120        * multiple SIGCHLD arrive at the same time, one of them can be
4121        * dropped (since a given UNIX signal can only be pending once).
4122        */
4123       for (node = unix_child_watches; node; node = node->next)
4124         {
4125           GChildWatchSource *source = node->data;
4126
4127           if (!source->child_exited)
4128             {
4129               if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4130                 {
4131                   source->child_exited = TRUE;
4132
4133                   wake_source ((GSource *) source);
4134                 }
4135             }
4136         }
4137     }
4138
4139   /* handle GUnixSignalWatchSource instances */
4140   for (node = unix_signal_watches; node; node = node->next)
4141     {
4142       GUnixSignalWatchSource *source = node->data;
4143
4144       if (!source->pending)
4145         {
4146           if (unix_signal_pending[source->signum])
4147             {
4148               unix_signal_pending[source->signum] = FALSE;
4149               source->pending = TRUE;
4150
4151               wake_source ((GSource *) source);
4152             }
4153         }
4154     }
4155
4156   G_UNLOCK(unix_signal_lock);
4157 }
4158
4159 static gboolean
4160 g_child_watch_prepare (GSource *source,
4161                        gint    *timeout)
4162 {
4163   GChildWatchSource *child_watch_source;
4164
4165   child_watch_source = (GChildWatchSource *) source;
4166
4167   return child_watch_source->child_exited;
4168 }
4169
4170 static gboolean
4171 g_child_watch_check (GSource *source)
4172 {
4173   GChildWatchSource *child_watch_source;
4174
4175   child_watch_source = (GChildWatchSource *) source;
4176
4177   return child_watch_source->child_exited;
4178 }
4179
4180 static gboolean
4181 g_unix_signal_watch_prepare (GSource *source,
4182                              gint    *timeout)
4183 {
4184   GUnixSignalWatchSource *unix_signal_source;
4185
4186   unix_signal_source = (GUnixSignalWatchSource *) source;
4187
4188   return unix_signal_source->pending;
4189 }
4190
4191 static gboolean
4192 g_unix_signal_watch_check (GSource  *source)
4193 {
4194   GUnixSignalWatchSource *unix_signal_source;
4195
4196   unix_signal_source = (GUnixSignalWatchSource *) source;
4197
4198   return unix_signal_source->pending;
4199 }
4200
4201 static gboolean
4202 g_unix_signal_watch_dispatch (GSource    *source, 
4203                               GSourceFunc callback,
4204                               gpointer    user_data)
4205 {
4206   GUnixSignalWatchSource *unix_signal_source;
4207
4208   unix_signal_source = (GUnixSignalWatchSource *) source;
4209
4210   if (!callback)
4211     {
4212       g_warning ("Unix signal source dispatched without callback\n"
4213                  "You must call g_source_set_callback().");
4214       return FALSE;
4215     }
4216
4217   (callback) (user_data);
4218
4219   unix_signal_source->pending = FALSE;
4220
4221   return TRUE;
4222 }
4223
4224 static void
4225 ensure_unix_signal_handler_installed_unlocked (int signum)
4226 {
4227   static sigset_t installed_signal_mask;
4228   static gboolean initialized;
4229   struct sigaction action;
4230
4231   if (!initialized)
4232     {
4233       sigemptyset (&installed_signal_mask);
4234       g_get_worker_context ();
4235       initialized = TRUE;
4236     }
4237
4238   if (sigismember (&installed_signal_mask, signum))
4239     return;
4240
4241   sigaddset (&installed_signal_mask, signum);
4242
4243   action.sa_handler = g_unix_signal_handler;
4244   sigemptyset (&action.sa_mask);
4245   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4246   sigaction (signum, &action, NULL);
4247 }
4248
4249 GSource *
4250 _g_main_create_unix_signal_watch (int signum)
4251 {
4252   GSource *source;
4253   GUnixSignalWatchSource *unix_signal_source;
4254
4255   source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4256   unix_signal_source = (GUnixSignalWatchSource *) source;
4257
4258   unix_signal_source->signum = signum;
4259   unix_signal_source->pending = FALSE;
4260
4261   G_LOCK (unix_signal_lock);
4262   ensure_unix_signal_handler_installed_unlocked (signum);
4263   unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4264   if (unix_signal_pending[signum])
4265     unix_signal_source->pending = TRUE;
4266   unix_signal_pending[signum] = FALSE;
4267   G_UNLOCK (unix_signal_lock);
4268
4269   return source;
4270 }
4271
4272 static void
4273 g_unix_signal_watch_finalize (GSource    *source)
4274 {
4275   G_LOCK (unix_signal_lock);
4276   unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4277   G_UNLOCK (unix_signal_lock);
4278 }
4279
4280 static void
4281 g_child_watch_finalize (GSource *source)
4282 {
4283   G_LOCK (unix_signal_lock);
4284   unix_child_watches = g_slist_remove (unix_child_watches, source);
4285   G_UNLOCK (unix_signal_lock);
4286 }
4287
4288 #endif /* G_OS_WIN32 */
4289
4290 static gboolean
4291 g_child_watch_dispatch (GSource    *source, 
4292                         GSourceFunc callback,
4293                         gpointer    user_data)
4294 {
4295   GChildWatchSource *child_watch_source;
4296   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4297
4298   child_watch_source = (GChildWatchSource *) source;
4299
4300   if (!callback)
4301     {
4302       g_warning ("Child watch source dispatched without callback\n"
4303                  "You must call g_source_set_callback().");
4304       return FALSE;
4305     }
4306
4307   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4308
4309   /* We never keep a child watch source around as the child is gone */
4310   return FALSE;
4311 }
4312
4313 #ifndef G_OS_WIN32
4314
4315 static void
4316 g_unix_signal_handler (int signum)
4317 {
4318   unix_signal_pending[signum] = TRUE;
4319   any_unix_signal_pending = TRUE;
4320
4321   g_wakeup_signal (glib_worker_context->wakeup);
4322 }
4323
4324 #endif /* !G_OS_WIN32 */
4325
4326 /**
4327  * g_child_watch_source_new:
4328  * @pid: process to watch. On POSIX the pid of a child process. On
4329  * Windows a handle for a process (which doesn't have to be a child).
4330  * 
4331  * Creates a new child_watch source.
4332  *
4333  * The source will not initially be associated with any #GMainContext
4334  * and must be added to one with g_source_attach() before it will be
4335  * executed.
4336  * 
4337  * Note that child watch sources can only be used in conjunction with
4338  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4339  * flag is used.
4340  *
4341  * Note that on platforms where #GPid must be explicitly closed
4342  * (see g_spawn_close_pid()) @pid must not be closed while the
4343  * source is still active. Typically, you will want to call
4344  * g_spawn_close_pid() in the callback function for the source.
4345  *
4346  * Note further that using g_child_watch_source_new() is not 
4347  * compatible with calling <literal>waitpid(-1)</literal> in 
4348  * the application. Calling waitpid() for individual pids will
4349  * still work fine. 
4350  * 
4351  * Return value: the newly-created child watch source
4352  *
4353  * Since: 2.4
4354  **/
4355 GSource *
4356 g_child_watch_source_new (GPid pid)
4357 {
4358   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4359   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4360
4361   child_watch_source->pid = pid;
4362
4363 #ifdef G_OS_WIN32
4364   child_watch_source->poll.fd = (gintptr) pid;
4365   child_watch_source->poll.events = G_IO_IN;
4366
4367   g_source_add_poll (source, &child_watch_source->poll);
4368 #else /* G_OS_WIN32 */
4369   G_LOCK (unix_signal_lock);
4370   ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4371   unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4372   if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4373     child_watch_source->child_exited = TRUE;
4374   G_UNLOCK (unix_signal_lock);
4375 #endif /* G_OS_WIN32 */
4376
4377   return source;
4378 }
4379
4380 /**
4381  * g_child_watch_add_full:
4382  * @priority: the priority of the idle source. Typically this will be in the
4383  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4384  * @pid:      process to watch. On POSIX the pid of a child process. On
4385  * Windows a handle for a process (which doesn't have to be a child).
4386  * @function: function to call
4387  * @data:     data to pass to @function
4388  * @notify:   function to call when the idle is removed, or %NULL
4389  * 
4390  * Sets a function to be called when the child indicated by @pid 
4391  * exits, at the priority @priority.
4392  *
4393  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4394  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4395  * the spawn function for the child watching to work.
4396  * 
4397  * Note that on platforms where #GPid must be explicitly closed
4398  * (see g_spawn_close_pid()) @pid must not be closed while the
4399  * source is still active. Typically, you will want to call
4400  * g_spawn_close_pid() in the callback function for the source.
4401  * 
4402  * GLib supports only a single callback per process id.
4403  *
4404  * This internally creates a main loop source using 
4405  * g_child_watch_source_new() and attaches it to the main loop context 
4406  * using g_source_attach(). You can do these steps manually if you 
4407  * need greater control.
4408  *
4409  * Return value: the ID (greater than 0) of the event source.
4410  *
4411  * Rename to: g_child_watch_add
4412  * Since: 2.4
4413  **/
4414 guint
4415 g_child_watch_add_full (gint            priority,
4416                         GPid            pid,
4417                         GChildWatchFunc function,
4418                         gpointer        data,
4419                         GDestroyNotify  notify)
4420 {
4421   GSource *source;
4422   guint id;
4423   
4424   g_return_val_if_fail (function != NULL, 0);
4425
4426   source = g_child_watch_source_new (pid);
4427
4428   if (priority != G_PRIORITY_DEFAULT)
4429     g_source_set_priority (source, priority);
4430
4431   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4432   id = g_source_attach (source, NULL);
4433   g_source_unref (source);
4434
4435   return id;
4436 }
4437
4438 /**
4439  * g_child_watch_add:
4440  * @pid:      process id to watch. On POSIX the pid of a child process. On
4441  * Windows a handle for a process (which doesn't have to be a child).
4442  * @function: function to call
4443  * @data:     data to pass to @function
4444  * 
4445  * Sets a function to be called when the child indicated by @pid 
4446  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4447  * 
4448  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4449  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4450  * the spawn function for the child watching to work.
4451  * 
4452  * Note that on platforms where #GPid must be explicitly closed
4453  * (see g_spawn_close_pid()) @pid must not be closed while the
4454  * source is still active. Typically, you will want to call
4455  * g_spawn_close_pid() in the callback function for the source.
4456  *
4457  * GLib supports only a single callback per process id.
4458  *
4459  * This internally creates a main loop source using 
4460  * g_child_watch_source_new() and attaches it to the main loop context 
4461  * using g_source_attach(). You can do these steps manually if you 
4462  * need greater control.
4463  *
4464  * Return value: the ID (greater than 0) of the event source.
4465  *
4466  * Since: 2.4
4467  **/
4468 guint 
4469 g_child_watch_add (GPid            pid,
4470                    GChildWatchFunc function,
4471                    gpointer        data)
4472 {
4473   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4474 }
4475
4476
4477 /* Idle functions */
4478
4479 static gboolean 
4480 g_idle_prepare  (GSource  *source,
4481                  gint     *timeout)
4482 {
4483   *timeout = 0;
4484
4485   return TRUE;
4486 }
4487
4488 static gboolean 
4489 g_idle_check    (GSource  *source)
4490 {
4491   return TRUE;
4492 }
4493
4494 static gboolean
4495 g_idle_dispatch (GSource    *source, 
4496                  GSourceFunc callback,
4497                  gpointer    user_data)
4498 {
4499   if (!callback)
4500     {
4501       g_warning ("Idle source dispatched without callback\n"
4502                  "You must call g_source_set_callback().");
4503       return FALSE;
4504     }
4505   
4506   return callback (user_data);
4507 }
4508
4509 /**
4510  * g_idle_source_new:
4511  * 
4512  * Creates a new idle source.
4513  *
4514  * The source will not initially be associated with any #GMainContext
4515  * and must be added to one with g_source_attach() before it will be
4516  * executed. Note that the default priority for idle sources is
4517  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4518  * have a default priority of %G_PRIORITY_DEFAULT.
4519  * 
4520  * Return value: the newly-created idle source
4521  **/
4522 GSource *
4523 g_idle_source_new (void)
4524 {
4525   GSource *source;
4526
4527   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4528   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4529
4530   return source;
4531 }
4532
4533 /**
4534  * g_idle_add_full:
4535  * @priority: the priority of the idle source. Typically this will be in the
4536  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4537  * @function: function to call
4538  * @data:     data to pass to @function
4539  * @notify:   function to call when the idle is removed, or %NULL
4540  * 
4541  * Adds a function to be called whenever there are no higher priority
4542  * events pending.  If the function returns %FALSE it is automatically
4543  * removed from the list of event sources and will not be called again.
4544  * 
4545  * This internally creates a main loop source using g_idle_source_new()
4546  * and attaches it to the main loop context using g_source_attach(). 
4547  * You can do these steps manually if you need greater control.
4548  * 
4549  * Return value: the ID (greater than 0) of the event source.
4550  * Rename to: g_idle_add
4551  **/
4552 guint 
4553 g_idle_add_full (gint           priority,
4554                  GSourceFunc    function,
4555                  gpointer       data,
4556                  GDestroyNotify notify)
4557 {
4558   GSource *source;
4559   guint id;
4560   
4561   g_return_val_if_fail (function != NULL, 0);
4562
4563   source = g_idle_source_new ();
4564
4565   if (priority != G_PRIORITY_DEFAULT_IDLE)
4566     g_source_set_priority (source, priority);
4567
4568   g_source_set_callback (source, function, data, notify);
4569   id = g_source_attach (source, NULL);
4570   g_source_unref (source);
4571
4572   return id;
4573 }
4574
4575 /**
4576  * g_idle_add:
4577  * @function: function to call 
4578  * @data: data to pass to @function.
4579  * 
4580  * Adds a function to be called whenever there are no higher priority
4581  * events pending to the default main loop. The function is given the
4582  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4583  * returns %FALSE it is automatically removed from the list of event
4584  * sources and will not be called again.
4585  * 
4586  * This internally creates a main loop source using g_idle_source_new()
4587  * and attaches it to the main loop context using g_source_attach(). 
4588  * You can do these steps manually if you need greater control.
4589  * 
4590  * Return value: the ID (greater than 0) of the event source.
4591  **/
4592 guint 
4593 g_idle_add (GSourceFunc    function,
4594             gpointer       data)
4595 {
4596   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4597 }
4598
4599 /**
4600  * g_idle_remove_by_data:
4601  * @data: the data for the idle source's callback.
4602  * 
4603  * Removes the idle function with the given data.
4604  * 
4605  * Return value: %TRUE if an idle source was found and removed.
4606  **/
4607 gboolean
4608 g_idle_remove_by_data (gpointer data)
4609 {
4610   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4611 }
4612
4613 /**
4614  * g_main_context_invoke:
4615  * @context: (allow-none): a #GMainContext, or %NULL
4616  * @function: function to call
4617  * @data: data to pass to @function
4618  *
4619  * Invokes a function in such a way that @context is owned during the
4620  * invocation of @function.
4621  *
4622  * If @context is %NULL then the global default main context — as
4623  * returned by g_main_context_default() — is used.
4624  *
4625  * If @context is owned by the current thread, @function is called
4626  * directly.  Otherwise, if @context is the thread-default main context
4627  * of the current thread and g_main_context_acquire() succeeds, then
4628  * @function is called and g_main_context_release() is called
4629  * afterwards.
4630  *
4631  * In any other case, an idle source is created to call @function and
4632  * that source is attached to @context (presumably to be run in another
4633  * thread).  The idle source is attached with #G_PRIORITY_DEFAULT
4634  * priority.  If you want a different priority, use
4635  * g_main_context_invoke_full().
4636  *
4637  * Note that, as with normal idle functions, @function should probably
4638  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
4639  * loop (and may prevent this call from returning).
4640  *
4641  * Since: 2.28
4642  **/
4643 void
4644 g_main_context_invoke (GMainContext *context,
4645                        GSourceFunc   function,
4646                        gpointer      data)
4647 {
4648   g_main_context_invoke_full (context,
4649                               G_PRIORITY_DEFAULT,
4650                               function, data, NULL);
4651 }
4652
4653 /**
4654  * g_main_context_invoke_full:
4655  * @context: (allow-none): a #GMainContext, or %NULL
4656  * @priority: the priority at which to run @function
4657  * @function: function to call
4658  * @data: data to pass to @function
4659  * @notify: a function to call when @data is no longer in use, or %NULL.
4660  *
4661  * Invokes a function in such a way that @context is owned during the
4662  * invocation of @function.
4663  *
4664  * This function is the same as g_main_context_invoke() except that it
4665  * lets you specify the priority incase @function ends up being
4666  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4667  *
4668  * @notify should not assume that it is called from any particular
4669  * thread or with any particular context acquired.
4670  *
4671  * Since: 2.28
4672  **/
4673 void
4674 g_main_context_invoke_full (GMainContext   *context,
4675                             gint            priority,
4676                             GSourceFunc     function,
4677                             gpointer        data,
4678                             GDestroyNotify  notify)
4679 {
4680   g_return_if_fail (function != NULL);
4681
4682   if (!context)
4683     context = g_main_context_default ();
4684
4685   if (g_main_context_is_owner (context))
4686     {
4687       while (function (data));
4688       if (notify != NULL)
4689         notify (data);
4690     }
4691
4692   else
4693     {
4694       GMainContext *thread_default;
4695
4696       thread_default = g_main_context_get_thread_default ();
4697
4698       if (!thread_default)
4699         thread_default = g_main_context_default ();
4700
4701       if (thread_default == context && g_main_context_acquire (context))
4702         {
4703           while (function (data));
4704
4705           g_main_context_release (context);
4706
4707           if (notify != NULL)
4708             notify (data);
4709         }
4710       else
4711         {
4712           GSource *source;
4713
4714           source = g_idle_source_new ();
4715           g_source_set_priority (source, priority);
4716           g_source_set_callback (source, function, data, notify);
4717           g_source_attach (source, context);
4718           g_source_unref (source);
4719         }
4720     }
4721 }
4722
4723 static gpointer
4724 glib_worker_main (gpointer data)
4725 {
4726   while (TRUE)
4727     {
4728       g_main_context_iteration (glib_worker_context, TRUE);
4729
4730 #ifdef G_OS_UNIX
4731       if (any_unix_signal_pending)
4732         dispatch_unix_signals ();
4733 #endif
4734     }
4735
4736   return NULL; /* worst GCC warning message ever... */
4737 }
4738
4739 GMainContext *
4740 g_get_worker_context (void)
4741 {
4742   static gsize initialised;
4743
4744   if (g_once_init_enter (&initialised))
4745     {
4746       /* mask all signals in the worker thread */
4747 #ifdef G_OS_UNIX
4748       sigset_t prev_mask;
4749       sigset_t all;
4750
4751       sigfillset (&all);
4752       pthread_sigmask (SIG_SETMASK, &all, &prev_mask);
4753 #endif
4754       glib_worker_context = g_main_context_new ();
4755       g_thread_new ("gmain", glib_worker_main, NULL);
4756 #ifdef G_OS_UNIX
4757       pthread_sigmask (SIG_SETMASK, &prev_mask, NULL);
4758 #endif
4759       g_once_init_leave (&initialised, TRUE);
4760     }
4761
4762   return glib_worker_context;
4763 }