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