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