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