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