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