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