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