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