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