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