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