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