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