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