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