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