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