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