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